From c5c1266ad9f2a509caa2d7d7cd20acf9277252e7 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 24 Feb 2023 02:29:35 +0000 Subject: [PATCH 1/2] chore: Update gapic-generator-python to v1.8.5 PiperOrigin-RevId: 511892190 Source-Link: https://github.com/googleapis/googleapis/commit/a45d9c09c1287ffdf938f4e8083e791046c0b23b Source-Link: https://github.com/googleapis/googleapis-gen/commit/1907294b1d8365ea24f8c5f2e059a64124c4ed3b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMTkwNzI5NGIxZDgzNjVlYTI0ZjhjNWYyZTA1OWE2NDEyNGM0ZWQzYiJ9 --- owl-bot-staging/v1/.coveragerc | 13 + owl-bot-staging/v1/.flake8 | 33 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + .../docs/apigee_registry_v1/provisioning.rst | 6 + .../v1/docs/apigee_registry_v1/registry.rst | 10 + .../v1/docs/apigee_registry_v1/services.rst | 7 + .../v1/docs/apigee_registry_v1/types.rst | 6 + owl-bot-staging/v1/docs/conf.py | 376 + owl-bot-staging/v1/docs/index.rst | 7 + .../google/cloud/apigee_registry/__init__.py | 135 + .../cloud/apigee_registry/gapic_version.py | 16 + .../v1/google/cloud/apigee_registry/py.typed | 2 + .../cloud/apigee_registry_v1/__init__.py | 136 + .../apigee_registry_v1/gapic_metadata.json | 617 + .../cloud/apigee_registry_v1/gapic_version.py | 16 + .../google/cloud/apigee_registry_v1/py.typed | 2 + .../apigee_registry_v1/services/__init__.py | 15 + .../services/provisioning/__init__.py | 22 + .../services/provisioning/async_client.py | 1166 + .../services/provisioning/client.py | 1365 + .../provisioning/transports/__init__.py | 38 + .../services/provisioning/transports/base.py | 269 + .../services/provisioning/transports/grpc.py | 527 + .../provisioning/transports/grpc_asyncio.py | 526 + .../services/provisioning/transports/rest.py | 1470 ++ .../services/registry/__init__.py | 22 + .../services/registry/async_client.py | 4984 ++++ .../services/registry/client.py | 4928 ++++ .../services/registry/pagers.py | 866 + .../services/registry/transports/__init__.py | 38 + .../services/registry/transports/base.py | 1010 + .../services/registry/transports/grpc.py | 1362 + .../registry/transports/grpc_asyncio.py | 1361 + .../services/registry/transports/rest.py | 5357 ++++ .../apigee_registry_v1/types/__init__.py | 128 + .../types/provisioning_service.py | 262 + .../types/registry_models.py | 573 + .../types/registry_service.py | 1222 + owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 184 + ...ated_provisioning_create_instance_async.py | 61 + ...rated_provisioning_create_instance_sync.py | 61 + ...ated_provisioning_delete_instance_async.py | 56 + ...rated_provisioning_delete_instance_sync.py | 56 + ...nerated_provisioning_get_instance_async.py | 52 + ...enerated_provisioning_get_instance_sync.py | 52 + ..._v1_generated_registry_create_api_async.py | 53 + ...ed_registry_create_api_deployment_async.py | 53 + ...ted_registry_create_api_deployment_sync.py | 53 + ...enerated_registry_create_api_spec_async.py | 53 + ...generated_registry_create_api_spec_sync.py | 53 + ...y_v1_generated_registry_create_api_sync.py | 53 + ...rated_registry_create_api_version_async.py | 53 + ...erated_registry_create_api_version_sync.py | 53 + ...enerated_registry_create_artifact_async.py | 53 + ...generated_registry_create_artifact_sync.py | 53 + ..._v1_generated_registry_delete_api_async.py | 50 + ...ed_registry_delete_api_deployment_async.py | 50 + ...ry_delete_api_deployment_revision_async.py | 52 + ...try_delete_api_deployment_revision_sync.py | 52 + ...ted_registry_delete_api_deployment_sync.py | 50 + ...enerated_registry_delete_api_spec_async.py | 50 + ...registry_delete_api_spec_revision_async.py | 52 + ..._registry_delete_api_spec_revision_sync.py | 52 + ...generated_registry_delete_api_spec_sync.py | 50 + ...y_v1_generated_registry_delete_api_sync.py | 50 + ...rated_registry_delete_api_version_async.py | 50 + ...erated_registry_delete_api_version_sync.py | 50 + ...enerated_registry_delete_artifact_async.py | 50 + ...generated_registry_delete_artifact_sync.py | 50 + ...try_v1_generated_registry_get_api_async.py | 52 + ...rated_registry_get_api_deployment_async.py | 52 + ...erated_registry_get_api_deployment_sync.py | 52 + ...1_generated_registry_get_api_spec_async.py | 52 + ...ed_registry_get_api_spec_contents_async.py | 52 + ...ted_registry_get_api_spec_contents_sync.py | 52 + ...v1_generated_registry_get_api_spec_sync.py | 52 + ...stry_v1_generated_registry_get_api_sync.py | 52 + ...enerated_registry_get_api_version_async.py | 52 + ...generated_registry_get_api_version_sync.py | 52 + ...1_generated_registry_get_artifact_async.py | 52 + ...ed_registry_get_artifact_contents_async.py | 52 + ...ted_registry_get_artifact_contents_sync.py | 52 + ...v1_generated_registry_get_artifact_sync.py | 52 + ...try_list_api_deployment_revisions_async.py | 53 + ...stry_list_api_deployment_revisions_sync.py | 53 + ...ted_registry_list_api_deployments_async.py | 53 + ...ated_registry_list_api_deployments_sync.py | 53 + ..._registry_list_api_spec_revisions_async.py | 53 + ...d_registry_list_api_spec_revisions_sync.py | 53 + ...generated_registry_list_api_specs_async.py | 53 + ..._generated_registry_list_api_specs_sync.py | 53 + ...erated_registry_list_api_versions_async.py | 53 + ...nerated_registry_list_api_versions_sync.py | 53 + ...y_v1_generated_registry_list_apis_async.py | 53 + ...ry_v1_generated_registry_list_apis_sync.py | 53 + ...generated_registry_list_artifacts_async.py | 53 + ..._generated_registry_list_artifacts_sync.py | 53 + ...nerated_registry_replace_artifact_async.py | 51 + ...enerated_registry_replace_artifact_sync.py | 51 + ..._registry_rollback_api_deployment_async.py | 53 + ...d_registry_rollback_api_deployment_sync.py | 53 + ...erated_registry_rollback_api_spec_async.py | 53 + ...nerated_registry_rollback_api_spec_sync.py | 53 + ...istry_tag_api_deployment_revision_async.py | 53 + ...gistry_tag_api_deployment_revision_sync.py | 53 + ...ed_registry_tag_api_spec_revision_async.py | 53 + ...ted_registry_tag_api_spec_revision_sync.py | 53 + ..._v1_generated_registry_update_api_async.py | 51 + ...ed_registry_update_api_deployment_async.py | 51 + ...ted_registry_update_api_deployment_sync.py | 51 + ...enerated_registry_update_api_spec_async.py | 51 + ...generated_registry_update_api_spec_sync.py | 51 + ...y_v1_generated_registry_update_api_sync.py | 51 + ...rated_registry_update_api_version_async.py | 51 + ...erated_registry_update_api_version_sync.py | 51 + ...tadata_google.cloud.apigeeregistry.v1.json | 6183 +++++ .../fixup_apigee_registry_v1_keywords.py | 213 + owl-bot-staging/v1/setup.py | 91 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.7.txt | 10 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + owl-bot-staging/v1/tests/__init__.py | 16 + owl-bot-staging/v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/apigee_registry_v1/__init__.py | 16 + .../apigee_registry_v1/test_provisioning.py | 4396 ++++ .../gapic/apigee_registry_v1/test_registry.py | 21303 ++++++++++++++++ 132 files changed, 65406 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc create mode 100644 owl-bot-staging/v1/.flake8 create mode 100644 owl-bot-staging/v1/MANIFEST.in create mode 100644 owl-bot-staging/v1/README.rst create mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst create mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst create mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/types.rst create mode 100644 owl-bot-staging/v1/docs/conf.py create mode 100644 owl-bot-staging/v1/docs/index.rst create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py create mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py create mode 100644 owl-bot-staging/v1/mypy.ini create mode 100644 owl-bot-staging/v1/noxfile.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py create mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1/tests/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 0000000..4deb36f --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/apigee_registry/__init__.py + google/cloud/apigee_registry/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 new file mode 100644 index 0000000..29227d4 --- /dev/null +++ b/owl-bot-staging/v1/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://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 by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in new file mode 100644 index 0000000..245d857 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/apigee_registry *.py +recursive-include google/cloud/apigee_registry_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 0000000..a6898f0 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Apigee Registry API +================================================= + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. Enable the Google Cloud Apigee Registry API. +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to +create isolated Python environments. The basic problem it addresses is one of +dependencies and versions, and indirectly permissions. + +With `virtualenv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ + + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv + source /bin/activate + /bin/pip install /path/to/library + + +Windows +^^^^^^^ + +.. code-block:: console + + python3 -m venv + \Scripts\activate + \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst new file mode 100644 index 0000000..08a647d --- /dev/null +++ b/owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst @@ -0,0 +1,6 @@ +Provisioning +------------------------------ + +.. automodule:: google.cloud.apigee_registry_v1.services.provisioning + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst new file mode 100644 index 0000000..dc4e73a --- /dev/null +++ b/owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst @@ -0,0 +1,10 @@ +Registry +-------------------------- + +.. automodule:: google.cloud.apigee_registry_v1.services.registry + :members: + :inherited-members: + +.. automodule:: google.cloud.apigee_registry_v1.services.registry.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/services.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/services.rst new file mode 100644 index 0000000..651781f --- /dev/null +++ b/owl-bot-staging/v1/docs/apigee_registry_v1/services.rst @@ -0,0 +1,7 @@ +Services for Google Cloud Apigee Registry v1 API +================================================ +.. toctree:: + :maxdepth: 2 + + provisioning + registry diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/types.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/types.rst new file mode 100644 index 0000000..ca720e7 --- /dev/null +++ b/owl-bot-staging/v1/docs/apigee_registry_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Apigee Registry v1 API +============================================= + +.. automodule:: google.cloud.apigee_registry_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py new file mode 100644 index 0000000..9d76789 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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. +# +# +# google-cloud-apigee-registry documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +import shlex + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +__version__ = "0.1.0" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "4.0.1" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_flags = ["members"] +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# Allow markdown includes (so releases.md can include CHANGLEOG.md) +# http://www.sphinx-doc.org/en/master/markdown.html +source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = u"google-cloud-apigee-registry" +copyright = u"2022, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-apigee-registry-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # 'preamble': '', + # Latex figure (float) alignment + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-cloud-apigee-registry.tex", + u"google-cloud-apigee-registry Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-cloud-apigee-registry", + u"Google Cloud Apigee Registry Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-cloud-apigee-registry", + u"google-cloud-apigee-registry Documentation", + author, + "google-cloud-apigee-registry", + "GAPIC library for Google Cloud Apigee Registry API", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("http://python.readthedocs.org/en/latest/", None), + "gax": ("https://gax-python.readthedocs.org/en/latest/", None), + "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), + "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), + "grpc": ("https://grpc.io/grpc/python/", None), + "requests": ("http://requests.kennethreitz.org/en/stable/", None), + "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst new file mode 100644 index 0000000..c450000 --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + apigee_registry_v1/services + apigee_registry_v1/types diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py new file mode 100644 index 0000000..8a876f3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py @@ -0,0 +1,135 @@ +# -*- 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. +# +from google.cloud.apigee_registry import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.apigee_registry_v1.services.provisioning.client import ProvisioningClient +from google.cloud.apigee_registry_v1.services.provisioning.async_client import ProvisioningAsyncClient +from google.cloud.apigee_registry_v1.services.registry.client import RegistryClient +from google.cloud.apigee_registry_v1.services.registry.async_client import RegistryAsyncClient + +from google.cloud.apigee_registry_v1.types.provisioning_service import CreateInstanceRequest +from google.cloud.apigee_registry_v1.types.provisioning_service import DeleteInstanceRequest +from google.cloud.apigee_registry_v1.types.provisioning_service import GetInstanceRequest +from google.cloud.apigee_registry_v1.types.provisioning_service import Instance +from google.cloud.apigee_registry_v1.types.provisioning_service import OperationMetadata +from google.cloud.apigee_registry_v1.types.registry_models import Api +from google.cloud.apigee_registry_v1.types.registry_models import ApiDeployment +from google.cloud.apigee_registry_v1.types.registry_models import ApiSpec +from google.cloud.apigee_registry_v1.types.registry_models import ApiVersion +from google.cloud.apigee_registry_v1.types.registry_models import Artifact +from google.cloud.apigee_registry_v1.types.registry_service import CreateApiDeploymentRequest +from google.cloud.apigee_registry_v1.types.registry_service import CreateApiRequest +from google.cloud.apigee_registry_v1.types.registry_service import CreateApiSpecRequest +from google.cloud.apigee_registry_v1.types.registry_service import CreateApiVersionRequest +from google.cloud.apigee_registry_v1.types.registry_service import CreateArtifactRequest +from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiDeploymentRequest +from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiDeploymentRevisionRequest +from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiRequest +from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiSpecRequest +from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiSpecRevisionRequest +from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiVersionRequest +from google.cloud.apigee_registry_v1.types.registry_service import DeleteArtifactRequest +from google.cloud.apigee_registry_v1.types.registry_service import GetApiDeploymentRequest +from google.cloud.apigee_registry_v1.types.registry_service import GetApiRequest +from google.cloud.apigee_registry_v1.types.registry_service import GetApiSpecContentsRequest +from google.cloud.apigee_registry_v1.types.registry_service import GetApiSpecRequest +from google.cloud.apigee_registry_v1.types.registry_service import GetApiVersionRequest +from google.cloud.apigee_registry_v1.types.registry_service import GetArtifactContentsRequest +from google.cloud.apigee_registry_v1.types.registry_service import GetArtifactRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentRevisionsRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentRevisionsResponse +from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentsRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentsResponse +from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecRevisionsRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecRevisionsResponse +from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecsRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecsResponse +from google.cloud.apigee_registry_v1.types.registry_service import ListApisRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListApisResponse +from google.cloud.apigee_registry_v1.types.registry_service import ListApiVersionsRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListApiVersionsResponse +from google.cloud.apigee_registry_v1.types.registry_service import ListArtifactsRequest +from google.cloud.apigee_registry_v1.types.registry_service import ListArtifactsResponse +from google.cloud.apigee_registry_v1.types.registry_service import ReplaceArtifactRequest +from google.cloud.apigee_registry_v1.types.registry_service import RollbackApiDeploymentRequest +from google.cloud.apigee_registry_v1.types.registry_service import RollbackApiSpecRequest +from google.cloud.apigee_registry_v1.types.registry_service import TagApiDeploymentRevisionRequest +from google.cloud.apigee_registry_v1.types.registry_service import TagApiSpecRevisionRequest +from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiDeploymentRequest +from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiRequest +from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiSpecRequest +from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiVersionRequest + +__all__ = ('ProvisioningClient', + 'ProvisioningAsyncClient', + 'RegistryClient', + 'RegistryAsyncClient', + 'CreateInstanceRequest', + 'DeleteInstanceRequest', + 'GetInstanceRequest', + 'Instance', + 'OperationMetadata', + 'Api', + 'ApiDeployment', + 'ApiSpec', + 'ApiVersion', + 'Artifact', + 'CreateApiDeploymentRequest', + 'CreateApiRequest', + 'CreateApiSpecRequest', + 'CreateApiVersionRequest', + 'CreateArtifactRequest', + 'DeleteApiDeploymentRequest', + 'DeleteApiDeploymentRevisionRequest', + 'DeleteApiRequest', + 'DeleteApiSpecRequest', + 'DeleteApiSpecRevisionRequest', + 'DeleteApiVersionRequest', + 'DeleteArtifactRequest', + 'GetApiDeploymentRequest', + 'GetApiRequest', + 'GetApiSpecContentsRequest', + 'GetApiSpecRequest', + 'GetApiVersionRequest', + 'GetArtifactContentsRequest', + 'GetArtifactRequest', + 'ListApiDeploymentRevisionsRequest', + 'ListApiDeploymentRevisionsResponse', + 'ListApiDeploymentsRequest', + 'ListApiDeploymentsResponse', + 'ListApiSpecRevisionsRequest', + 'ListApiSpecRevisionsResponse', + 'ListApiSpecsRequest', + 'ListApiSpecsResponse', + 'ListApisRequest', + 'ListApisResponse', + 'ListApiVersionsRequest', + 'ListApiVersionsResponse', + 'ListArtifactsRequest', + 'ListArtifactsResponse', + 'ReplaceArtifactRequest', + 'RollbackApiDeploymentRequest', + 'RollbackApiSpecRequest', + 'TagApiDeploymentRevisionRequest', + 'TagApiSpecRevisionRequest', + 'UpdateApiDeploymentRequest', + 'UpdateApiRequest', + 'UpdateApiSpecRequest', + 'UpdateApiVersionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py b/owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry/py.typed b/owl-bot-staging/v1/google/cloud/apigee_registry/py.typed new file mode 100644 index 0000000..4602793 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-apigee-registry package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py new file mode 100644 index 0000000..83d259d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py @@ -0,0 +1,136 @@ +# -*- 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. +# +from google.cloud.apigee_registry_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.provisioning import ProvisioningClient +from .services.provisioning import ProvisioningAsyncClient +from .services.registry import RegistryClient +from .services.registry import RegistryAsyncClient + +from .types.provisioning_service import CreateInstanceRequest +from .types.provisioning_service import DeleteInstanceRequest +from .types.provisioning_service import GetInstanceRequest +from .types.provisioning_service import Instance +from .types.provisioning_service import OperationMetadata +from .types.registry_models import Api +from .types.registry_models import ApiDeployment +from .types.registry_models import ApiSpec +from .types.registry_models import ApiVersion +from .types.registry_models import Artifact +from .types.registry_service import CreateApiDeploymentRequest +from .types.registry_service import CreateApiRequest +from .types.registry_service import CreateApiSpecRequest +from .types.registry_service import CreateApiVersionRequest +from .types.registry_service import CreateArtifactRequest +from .types.registry_service import DeleteApiDeploymentRequest +from .types.registry_service import DeleteApiDeploymentRevisionRequest +from .types.registry_service import DeleteApiRequest +from .types.registry_service import DeleteApiSpecRequest +from .types.registry_service import DeleteApiSpecRevisionRequest +from .types.registry_service import DeleteApiVersionRequest +from .types.registry_service import DeleteArtifactRequest +from .types.registry_service import GetApiDeploymentRequest +from .types.registry_service import GetApiRequest +from .types.registry_service import GetApiSpecContentsRequest +from .types.registry_service import GetApiSpecRequest +from .types.registry_service import GetApiVersionRequest +from .types.registry_service import GetArtifactContentsRequest +from .types.registry_service import GetArtifactRequest +from .types.registry_service import ListApiDeploymentRevisionsRequest +from .types.registry_service import ListApiDeploymentRevisionsResponse +from .types.registry_service import ListApiDeploymentsRequest +from .types.registry_service import ListApiDeploymentsResponse +from .types.registry_service import ListApiSpecRevisionsRequest +from .types.registry_service import ListApiSpecRevisionsResponse +from .types.registry_service import ListApiSpecsRequest +from .types.registry_service import ListApiSpecsResponse +from .types.registry_service import ListApisRequest +from .types.registry_service import ListApisResponse +from .types.registry_service import ListApiVersionsRequest +from .types.registry_service import ListApiVersionsResponse +from .types.registry_service import ListArtifactsRequest +from .types.registry_service import ListArtifactsResponse +from .types.registry_service import ReplaceArtifactRequest +from .types.registry_service import RollbackApiDeploymentRequest +from .types.registry_service import RollbackApiSpecRequest +from .types.registry_service import TagApiDeploymentRevisionRequest +from .types.registry_service import TagApiSpecRevisionRequest +from .types.registry_service import UpdateApiDeploymentRequest +from .types.registry_service import UpdateApiRequest +from .types.registry_service import UpdateApiSpecRequest +from .types.registry_service import UpdateApiVersionRequest + +__all__ = ( + 'ProvisioningAsyncClient', + 'RegistryAsyncClient', +'Api', +'ApiDeployment', +'ApiSpec', +'ApiVersion', +'Artifact', +'CreateApiDeploymentRequest', +'CreateApiRequest', +'CreateApiSpecRequest', +'CreateApiVersionRequest', +'CreateArtifactRequest', +'CreateInstanceRequest', +'DeleteApiDeploymentRequest', +'DeleteApiDeploymentRevisionRequest', +'DeleteApiRequest', +'DeleteApiSpecRequest', +'DeleteApiSpecRevisionRequest', +'DeleteApiVersionRequest', +'DeleteArtifactRequest', +'DeleteInstanceRequest', +'GetApiDeploymentRequest', +'GetApiRequest', +'GetApiSpecContentsRequest', +'GetApiSpecRequest', +'GetApiVersionRequest', +'GetArtifactContentsRequest', +'GetArtifactRequest', +'GetInstanceRequest', +'Instance', +'ListApiDeploymentRevisionsRequest', +'ListApiDeploymentRevisionsResponse', +'ListApiDeploymentsRequest', +'ListApiDeploymentsResponse', +'ListApiSpecRevisionsRequest', +'ListApiSpecRevisionsResponse', +'ListApiSpecsRequest', +'ListApiSpecsResponse', +'ListApiVersionsRequest', +'ListApiVersionsResponse', +'ListApisRequest', +'ListApisResponse', +'ListArtifactsRequest', +'ListArtifactsResponse', +'OperationMetadata', +'ProvisioningClient', +'RegistryClient', +'ReplaceArtifactRequest', +'RollbackApiDeploymentRequest', +'RollbackApiSpecRequest', +'TagApiDeploymentRevisionRequest', +'TagApiSpecRevisionRequest', +'UpdateApiDeploymentRequest', +'UpdateApiRequest', +'UpdateApiSpecRequest', +'UpdateApiVersionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json new file mode 100644 index 0000000..20b6f38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json @@ -0,0 +1,617 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.apigee_registry_v1", + "protoPackage": "google.cloud.apigeeregistry.v1", + "schema": "1.0", + "services": { + "Provisioning": { + "clients": { + "grpc": { + "libraryClient": "ProvisioningClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ProvisioningAsyncClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + } + } + }, + "rest": { + "libraryClient": "ProvisioningClient", + "rpcs": { + "CreateInstance": { + "methods": [ + "create_instance" + ] + }, + "DeleteInstance": { + "methods": [ + "delete_instance" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + } + } + } + } + }, + "Registry": { + "clients": { + "grpc": { + "libraryClient": "RegistryClient", + "rpcs": { + "CreateApi": { + "methods": [ + "create_api" + ] + }, + "CreateApiDeployment": { + "methods": [ + "create_api_deployment" + ] + }, + "CreateApiSpec": { + "methods": [ + "create_api_spec" + ] + }, + "CreateApiVersion": { + "methods": [ + "create_api_version" + ] + }, + "CreateArtifact": { + "methods": [ + "create_artifact" + ] + }, + "DeleteApi": { + "methods": [ + "delete_api" + ] + }, + "DeleteApiDeployment": { + "methods": [ + "delete_api_deployment" + ] + }, + "DeleteApiDeploymentRevision": { + "methods": [ + "delete_api_deployment_revision" + ] + }, + "DeleteApiSpec": { + "methods": [ + "delete_api_spec" + ] + }, + "DeleteApiSpecRevision": { + "methods": [ + "delete_api_spec_revision" + ] + }, + "DeleteApiVersion": { + "methods": [ + "delete_api_version" + ] + }, + "DeleteArtifact": { + "methods": [ + "delete_artifact" + ] + }, + "GetApi": { + "methods": [ + "get_api" + ] + }, + "GetApiDeployment": { + "methods": [ + "get_api_deployment" + ] + }, + "GetApiSpec": { + "methods": [ + "get_api_spec" + ] + }, + "GetApiSpecContents": { + "methods": [ + "get_api_spec_contents" + ] + }, + "GetApiVersion": { + "methods": [ + "get_api_version" + ] + }, + "GetArtifact": { + "methods": [ + "get_artifact" + ] + }, + "GetArtifactContents": { + "methods": [ + "get_artifact_contents" + ] + }, + "ListApiDeploymentRevisions": { + "methods": [ + "list_api_deployment_revisions" + ] + }, + "ListApiDeployments": { + "methods": [ + "list_api_deployments" + ] + }, + "ListApiSpecRevisions": { + "methods": [ + "list_api_spec_revisions" + ] + }, + "ListApiSpecs": { + "methods": [ + "list_api_specs" + ] + }, + "ListApiVersions": { + "methods": [ + "list_api_versions" + ] + }, + "ListApis": { + "methods": [ + "list_apis" + ] + }, + "ListArtifacts": { + "methods": [ + "list_artifacts" + ] + }, + "ReplaceArtifact": { + "methods": [ + "replace_artifact" + ] + }, + "RollbackApiDeployment": { + "methods": [ + "rollback_api_deployment" + ] + }, + "RollbackApiSpec": { + "methods": [ + "rollback_api_spec" + ] + }, + "TagApiDeploymentRevision": { + "methods": [ + "tag_api_deployment_revision" + ] + }, + "TagApiSpecRevision": { + "methods": [ + "tag_api_spec_revision" + ] + }, + "UpdateApi": { + "methods": [ + "update_api" + ] + }, + "UpdateApiDeployment": { + "methods": [ + "update_api_deployment" + ] + }, + "UpdateApiSpec": { + "methods": [ + "update_api_spec" + ] + }, + "UpdateApiVersion": { + "methods": [ + "update_api_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RegistryAsyncClient", + "rpcs": { + "CreateApi": { + "methods": [ + "create_api" + ] + }, + "CreateApiDeployment": { + "methods": [ + "create_api_deployment" + ] + }, + "CreateApiSpec": { + "methods": [ + "create_api_spec" + ] + }, + "CreateApiVersion": { + "methods": [ + "create_api_version" + ] + }, + "CreateArtifact": { + "methods": [ + "create_artifact" + ] + }, + "DeleteApi": { + "methods": [ + "delete_api" + ] + }, + "DeleteApiDeployment": { + "methods": [ + "delete_api_deployment" + ] + }, + "DeleteApiDeploymentRevision": { + "methods": [ + "delete_api_deployment_revision" + ] + }, + "DeleteApiSpec": { + "methods": [ + "delete_api_spec" + ] + }, + "DeleteApiSpecRevision": { + "methods": [ + "delete_api_spec_revision" + ] + }, + "DeleteApiVersion": { + "methods": [ + "delete_api_version" + ] + }, + "DeleteArtifact": { + "methods": [ + "delete_artifact" + ] + }, + "GetApi": { + "methods": [ + "get_api" + ] + }, + "GetApiDeployment": { + "methods": [ + "get_api_deployment" + ] + }, + "GetApiSpec": { + "methods": [ + "get_api_spec" + ] + }, + "GetApiSpecContents": { + "methods": [ + "get_api_spec_contents" + ] + }, + "GetApiVersion": { + "methods": [ + "get_api_version" + ] + }, + "GetArtifact": { + "methods": [ + "get_artifact" + ] + }, + "GetArtifactContents": { + "methods": [ + "get_artifact_contents" + ] + }, + "ListApiDeploymentRevisions": { + "methods": [ + "list_api_deployment_revisions" + ] + }, + "ListApiDeployments": { + "methods": [ + "list_api_deployments" + ] + }, + "ListApiSpecRevisions": { + "methods": [ + "list_api_spec_revisions" + ] + }, + "ListApiSpecs": { + "methods": [ + "list_api_specs" + ] + }, + "ListApiVersions": { + "methods": [ + "list_api_versions" + ] + }, + "ListApis": { + "methods": [ + "list_apis" + ] + }, + "ListArtifacts": { + "methods": [ + "list_artifacts" + ] + }, + "ReplaceArtifact": { + "methods": [ + "replace_artifact" + ] + }, + "RollbackApiDeployment": { + "methods": [ + "rollback_api_deployment" + ] + }, + "RollbackApiSpec": { + "methods": [ + "rollback_api_spec" + ] + }, + "TagApiDeploymentRevision": { + "methods": [ + "tag_api_deployment_revision" + ] + }, + "TagApiSpecRevision": { + "methods": [ + "tag_api_spec_revision" + ] + }, + "UpdateApi": { + "methods": [ + "update_api" + ] + }, + "UpdateApiDeployment": { + "methods": [ + "update_api_deployment" + ] + }, + "UpdateApiSpec": { + "methods": [ + "update_api_spec" + ] + }, + "UpdateApiVersion": { + "methods": [ + "update_api_version" + ] + } + } + }, + "rest": { + "libraryClient": "RegistryClient", + "rpcs": { + "CreateApi": { + "methods": [ + "create_api" + ] + }, + "CreateApiDeployment": { + "methods": [ + "create_api_deployment" + ] + }, + "CreateApiSpec": { + "methods": [ + "create_api_spec" + ] + }, + "CreateApiVersion": { + "methods": [ + "create_api_version" + ] + }, + "CreateArtifact": { + "methods": [ + "create_artifact" + ] + }, + "DeleteApi": { + "methods": [ + "delete_api" + ] + }, + "DeleteApiDeployment": { + "methods": [ + "delete_api_deployment" + ] + }, + "DeleteApiDeploymentRevision": { + "methods": [ + "delete_api_deployment_revision" + ] + }, + "DeleteApiSpec": { + "methods": [ + "delete_api_spec" + ] + }, + "DeleteApiSpecRevision": { + "methods": [ + "delete_api_spec_revision" + ] + }, + "DeleteApiVersion": { + "methods": [ + "delete_api_version" + ] + }, + "DeleteArtifact": { + "methods": [ + "delete_artifact" + ] + }, + "GetApi": { + "methods": [ + "get_api" + ] + }, + "GetApiDeployment": { + "methods": [ + "get_api_deployment" + ] + }, + "GetApiSpec": { + "methods": [ + "get_api_spec" + ] + }, + "GetApiSpecContents": { + "methods": [ + "get_api_spec_contents" + ] + }, + "GetApiVersion": { + "methods": [ + "get_api_version" + ] + }, + "GetArtifact": { + "methods": [ + "get_artifact" + ] + }, + "GetArtifactContents": { + "methods": [ + "get_artifact_contents" + ] + }, + "ListApiDeploymentRevisions": { + "methods": [ + "list_api_deployment_revisions" + ] + }, + "ListApiDeployments": { + "methods": [ + "list_api_deployments" + ] + }, + "ListApiSpecRevisions": { + "methods": [ + "list_api_spec_revisions" + ] + }, + "ListApiSpecs": { + "methods": [ + "list_api_specs" + ] + }, + "ListApiVersions": { + "methods": [ + "list_api_versions" + ] + }, + "ListApis": { + "methods": [ + "list_apis" + ] + }, + "ListArtifacts": { + "methods": [ + "list_artifacts" + ] + }, + "ReplaceArtifact": { + "methods": [ + "replace_artifact" + ] + }, + "RollbackApiDeployment": { + "methods": [ + "rollback_api_deployment" + ] + }, + "RollbackApiSpec": { + "methods": [ + "rollback_api_spec" + ] + }, + "TagApiDeploymentRevision": { + "methods": [ + "tag_api_deployment_revision" + ] + }, + "TagApiSpecRevision": { + "methods": [ + "tag_api_spec_revision" + ] + }, + "UpdateApi": { + "methods": [ + "update_api" + ] + }, + "UpdateApiDeployment": { + "methods": [ + "update_api_deployment" + ] + }, + "UpdateApiSpec": { + "methods": [ + "update_api_spec" + ] + }, + "UpdateApiVersion": { + "methods": [ + "update_api_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py new file mode 100644 index 0000000..405b1ce --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- 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. +# +__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed new file mode 100644 index 0000000..4602793 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-apigee-registry package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py new file mode 100644 index 0000000..e8e1c38 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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. +# diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py new file mode 100644 index 0000000..475c17b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py @@ -0,0 +1,22 @@ +# -*- 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. +# +from .client import ProvisioningClient +from .async_client import ProvisioningAsyncClient + +__all__ = ( + 'ProvisioningClient', + 'ProvisioningAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py new file mode 100644 index 0000000..5a9da91 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py @@ -0,0 +1,1166 @@ +# -*- 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. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.apigee_registry_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.apigee_registry_v1.types import provisioning_service +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 empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ProvisioningTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProvisioningGrpcAsyncIOTransport +from .client import ProvisioningClient + + +class ProvisioningAsyncClient: + """The service that is used for managing the data plane + provisioning of the Registry. + """ + + _client: ProvisioningClient + + DEFAULT_ENDPOINT = ProvisioningClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProvisioningClient.DEFAULT_MTLS_ENDPOINT + + instance_path = staticmethod(ProvisioningClient.instance_path) + parse_instance_path = staticmethod(ProvisioningClient.parse_instance_path) + common_billing_account_path = staticmethod(ProvisioningClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(ProvisioningClient.parse_common_billing_account_path) + common_folder_path = staticmethod(ProvisioningClient.common_folder_path) + parse_common_folder_path = staticmethod(ProvisioningClient.parse_common_folder_path) + common_organization_path = staticmethod(ProvisioningClient.common_organization_path) + parse_common_organization_path = staticmethod(ProvisioningClient.parse_common_organization_path) + common_project_path = staticmethod(ProvisioningClient.common_project_path) + parse_common_project_path = staticmethod(ProvisioningClient.parse_common_project_path) + common_location_path = staticmethod(ProvisioningClient.common_location_path) + parse_common_location_path = staticmethod(ProvisioningClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProvisioningAsyncClient: The constructed client. + """ + return ProvisioningClient.from_service_account_info.__func__(ProvisioningAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProvisioningAsyncClient: The constructed client. + """ + return ProvisioningClient.from_service_account_file.__func__(ProvisioningAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + 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 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. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ProvisioningClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ProvisioningTransport: + """Returns the transport used by the client instance. + + Returns: + ProvisioningTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(ProvisioningClient).get_transport_class, type(ProvisioningClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, ProvisioningTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the provisioning client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProvisioningTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ProvisioningClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_instance(self, + request: Optional[Union[provisioning_service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[provisioning_service.Instance] = None, + instance_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Provisions instance resources for the Registry. + + .. 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 apigee_registry_v1 + + async def sample_create_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningAsyncClient() + + # Initialize request argument(s) + instance = apigee_registry_v1.Instance() + instance.config.cmek_key_name = "cmek_key_name_value" + + request = apigee_registry_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateInstanceRequest, dict]]): + The request object. Request message for CreateInstance. + parent (:class:`str`): + Required. Parent resource of the Instance, of the form: + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (:class:`google.cloud.apigee_registry_v1.types.Instance`): + Required. The Instance. + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (:class:`str`): + Required. Identifier to assign to the + Instance. Must be unique within scope of + the parent resource. + + This corresponds to the ``instance_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.apigee_registry_v1.types.Instance` An Instance represents the instance resources of the Registry. + Currently, only one instance is allowed for each + project. + + """ + # 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, instance, instance_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = provisioning_service.CreateInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_instance, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + provisioning_service.Instance, + metadata_type=provisioning_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_instance(self, + request: Optional[Union[provisioning_service.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the Registry instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import apigee_registry_v1 + + async def sample_delete_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteInstanceRequest, dict]]): + The request object. Request message for DeleteInstance. + name (:class:`str`): + Required. The name of the Instance to delete. Format: + ``projects/*/locations/*/instances/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = provisioning_service.DeleteInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_instance, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=provisioning_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_instance(self, + request: Optional[Union[provisioning_service.GetInstanceRequest, 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]] = (), + ) -> provisioning_service.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import apigee_registry_v1 + + async def sample_get_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetInstanceRequest, dict]]): + The request object. Request message for GetInstance. + name (:class:`str`): + Required. The name of the Instance to retrieve. Format: + ``projects/*/locations/*/instances/*``. + + 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.apigee_registry_v1.types.Instance: + An Instance represents the instance + resources of the Registry. Currently, + only one instance is allowed for each + project. + + """ + # 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 = provisioning_service.GetInstanceRequest(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_instance, + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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 + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "ProvisioningAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py new file mode 100644 index 0000000..86ef821 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py @@ -0,0 +1,1365 @@ +# -*- 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. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.apigee_registry_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.apigee_registry_v1.types import provisioning_service +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 empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import ProvisioningTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProvisioningGrpcTransport +from .transports.grpc_asyncio import ProvisioningGrpcAsyncIOTransport +from .transports.rest import ProvisioningRestTransport + + +class ProvisioningClientMeta(type): + """Metaclass for the Provisioning client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[ProvisioningTransport]] + _transport_registry["grpc"] = ProvisioningGrpcTransport + _transport_registry["grpc_asyncio"] = ProvisioningGrpcAsyncIOTransport + _transport_registry["rest"] = ProvisioningRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[ProvisioningTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ProvisioningClient(metaclass=ProvisioningClientMeta): + """The service that is used for managing the data plane + provisioning of the Registry. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "apigeeregistry.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProvisioningClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ProvisioningClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ProvisioningTransport: + """Returns the transport used by the client instance. + + Returns: + ProvisioningTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def instance_path(project: str,location: str,instance: str,) -> str: + """Returns a fully-qualified instance string.""" + return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + + @staticmethod + def parse_instance_path(path: str) -> Dict[str,str]: + """Parses a instance path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + 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 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. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, ProvisioningTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the provisioning client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ProvisioningTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProvisioningTransport): + # transport is a ProvisioningTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def create_instance(self, + request: Optional[Union[provisioning_service.CreateInstanceRequest, dict]] = None, + *, + parent: Optional[str] = None, + instance: Optional[provisioning_service.Instance] = None, + instance_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Provisions instance resources for the Registry. + + .. 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 apigee_registry_v1 + + def sample_create_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningClient() + + # Initialize request argument(s) + instance = apigee_registry_v1.Instance() + instance.config.cmek_key_name = "cmek_key_name_value" + + request = apigee_registry_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.CreateInstanceRequest, dict]): + The request object. Request message for CreateInstance. + parent (str): + Required. Parent resource of the Instance, of the form: + ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance (google.cloud.apigee_registry_v1.types.Instance): + Required. The Instance. + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + instance_id (str): + Required. Identifier to assign to the + Instance. Must be unique within scope of + the parent resource. + + This corresponds to the ``instance_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.apigee_registry_v1.types.Instance` An Instance represents the instance resources of the Registry. + Currently, only one instance is allowed for each + project. + + """ + # 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, instance, instance_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a provisioning_service.CreateInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, provisioning_service.CreateInstanceRequest): + request = provisioning_service.CreateInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if instance is not None: + request.instance = instance + if instance_id is not None: + request.instance_id = instance_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_instance] + + # 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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + provisioning_service.Instance, + metadata_type=provisioning_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_instance(self, + request: Optional[Union[provisioning_service.DeleteInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes the Registry instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import apigee_registry_v1 + + def sample_delete_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteInstanceRequest, dict]): + The request object. Request message for DeleteInstance. + name (str): + Required. The name of the Instance to delete. Format: + ``projects/*/locations/*/instances/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a provisioning_service.DeleteInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, provisioning_service.DeleteInstanceRequest): + request = provisioning_service.DeleteInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=provisioning_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_instance(self, + request: Optional[Union[provisioning_service.GetInstanceRequest, 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]] = (), + ) -> provisioning_service.Instance: + r"""Gets details of a single Instance. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import apigee_registry_v1 + + def sample_get_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetInstanceRequest, dict]): + The request object. Request message for GetInstance. + name (str): + Required. The name of the Instance to retrieve. Format: + ``projects/*/locations/*/instances/*``. + + 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.apigee_registry_v1.types.Instance: + An Instance represents the instance + resources of the Registry. Currently, + only one instance is allowed for each + project. + + """ + # 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 provisioning_service.GetInstanceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, provisioning_service.GetInstanceRequest): + request = provisioning_service.GetInstanceRequest(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_instance] + + # 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) -> "ProvisioningClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__) + + +__all__ = ( + "ProvisioningClient", +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py new file mode 100644 index 0000000..65fbb49 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import ProvisioningTransport +from .grpc import ProvisioningGrpcTransport +from .grpc_asyncio import ProvisioningGrpcAsyncIOTransport +from .rest import ProvisioningRestTransport +from .rest import ProvisioningRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProvisioningTransport]] +_transport_registry['grpc'] = ProvisioningGrpcTransport +_transport_registry['grpc_asyncio'] = ProvisioningGrpcAsyncIOTransport +_transport_registry['rest'] = ProvisioningRestTransport + +__all__ = ( + 'ProvisioningTransport', + 'ProvisioningGrpcTransport', + 'ProvisioningGrpcAsyncIOTransport', + 'ProvisioningRestTransport', + 'ProvisioningRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py new file mode 100644 index 0000000..3cf016f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py @@ -0,0 +1,269 @@ +# -*- 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.apigee_registry_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.apigee_registry_v1.types import provisioning_service +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.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class ProvisioningTransport(abc.ABC): + """Abstract transport class for Provisioning.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'apigeeregistry.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_instance: gapic_v1.method.wrap_method( + self.create_instance, + default_timeout=None, + client_info=client_info, + ), + self.delete_instance: gapic_v1.method.wrap_method( + self.delete_instance, + default_timeout=None, + client_info=client_info, + ), + self.get_instance: gapic_v1.method.wrap_method( + self.get_instance, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_instance(self) -> Callable[ + [provisioning_service.CreateInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def delete_instance(self) -> Callable[ + [provisioning_service.DeleteInstanceRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_instance(self) -> Callable[ + [provisioning_service.GetInstanceRequest], + Union[ + provisioning_service.Instance, + Awaitable[provisioning_service.Instance] + ]]: + 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 set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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() + + +__all__ = ( + 'ProvisioningTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py new file mode 100644 index 0000000..af6ec37 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py @@ -0,0 +1,527 @@ +# -*- 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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import operations_v1 +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.apigee_registry_v1.types import provisioning_service +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.longrunning import operations_pb2 # type: ignore +from .base import ProvisioningTransport, DEFAULT_CLIENT_INFO + + +class ProvisioningGrpcTransport(ProvisioningTransport): + """gRPC backend transport for Provisioning. + + The service that is used for managing the data plane + provisioning of the Registry. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_instance(self) -> Callable[ + [provisioning_service.CreateInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the create instance method over gRPC. + + Provisions instance resources for the Registry. + + Returns: + Callable[[~.CreateInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Provisioning/CreateInstance', + request_serializer=provisioning_service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def delete_instance(self) -> Callable[ + [provisioning_service.DeleteInstanceRequest], + operations_pb2.Operation]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes the Registry instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Provisioning/DeleteInstance', + request_serializer=provisioning_service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def get_instance(self) -> Callable[ + [provisioning_service.GetInstanceRequest], + provisioning_service.Instance]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + ~.Instance]: + 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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Provisioning/GetInstance', + request_serializer=provisioning_service.GetInstanceRequest.serialize, + response_deserializer=provisioning_service.Instance.deserialize, + ) + return self._stubs['get_instance'] + + 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'ProvisioningGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py new file mode 100644 index 0000000..0ffd095 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py @@ -0,0 +1,526 @@ +# -*- 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. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.apigee_registry_v1.types import provisioning_service +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.longrunning import operations_pb2 # type: ignore +from .base import ProvisioningTransport, DEFAULT_CLIENT_INFO +from .grpc import ProvisioningGrpcTransport + + +class ProvisioningGrpcAsyncIOTransport(ProvisioningTransport): + """gRPC AsyncIO backend transport for Provisioning. + + The service that is used for managing the data plane + provisioning of the Registry. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def create_instance(self) -> Callable[ + [provisioning_service.CreateInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create instance method over gRPC. + + Provisions instance resources for the Registry. + + Returns: + Callable[[~.CreateInstanceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_instance' not in self._stubs: + self._stubs['create_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Provisioning/CreateInstance', + request_serializer=provisioning_service.CreateInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_instance'] + + @property + def delete_instance(self) -> Callable[ + [provisioning_service.DeleteInstanceRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the delete instance method over gRPC. + + Deletes the Registry instance. + + Returns: + Callable[[~.DeleteInstanceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_instance' not in self._stubs: + self._stubs['delete_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Provisioning/DeleteInstance', + request_serializer=provisioning_service.DeleteInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['delete_instance'] + + @property + def get_instance(self) -> Callable[ + [provisioning_service.GetInstanceRequest], + Awaitable[provisioning_service.Instance]]: + r"""Return a callable for the get instance method over gRPC. + + Gets details of a single Instance. + + Returns: + Callable[[~.GetInstanceRequest], + Awaitable[~.Instance]]: + 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_instance' not in self._stubs: + self._stubs['get_instance'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Provisioning/GetInstance', + request_serializer=provisioning_service.GetInstanceRequest.serialize, + response_deserializer=provisioning_service.Instance.deserialize, + ) + return self._stubs['get_instance'] + + 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"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'ProvisioningGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py new file mode 100644 index 0000000..f796320 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py @@ -0,0 +1,1470 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.apigee_registry_v1.types import provisioning_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import ProvisioningTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ProvisioningRestInterceptor: + """Interceptor for Provisioning. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ProvisioningRestTransport. + + .. code-block:: python + class MyCustomProvisioningInterceptor(ProvisioningRestInterceptor): + def pre_create_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ProvisioningRestTransport(interceptor=MyCustomProvisioningInterceptor()) + client = ProvisioningClient(transport=transport) + + + """ + def pre_create_instance(self, request: provisioning_service.CreateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[provisioning_service.CreateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_instance + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_delete_instance(self, request: provisioning_service.DeleteInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[provisioning_service.DeleteInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_instance + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_get_instance(self, request: provisioning_service.GetInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[provisioning_service.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_get_instance(self, response: provisioning_service.Instance) -> provisioning_service.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Provisioning server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Provisioning server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ProvisioningRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProvisioningRestInterceptor + + +class ProvisioningRestTransport(ProvisioningTransport): + """REST backend transport for Provisioning. + + The service that is used for managing the data plane + provisioning of the Registry. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[ProvisioningRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ProvisioningRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + 'google.longrunning.Operations.CancelOperation': [ + { + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ], + 'google.longrunning.Operations.DeleteOperation': [ + { + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ], + 'google.longrunning.Operations.ListOperations': [ + { + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1") + + self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) + + # Return the client from cache. + return self._operations_client + + class _CreateInstance(ProvisioningRestStub): + def __hash__(self): + return hash("CreateInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "instanceId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: provisioning_service.CreateInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.provisioning_service.CreateInstanceRequest): + The request object. Request message for CreateInstance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/instances', + 'body': 'instance', + }, + ] + request, metadata = self._interceptor.pre_create_instance(request, metadata) + pb_request = provisioning_service.CreateInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_instance(resp) + return resp + + class _DeleteInstance(ProvisioningRestStub): + def __hash__(self): + return hash("DeleteInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: provisioning_service.DeleteInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.provisioning_service.DeleteInstanceRequest): + The request object. Request message for DeleteInstance. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + pb_request = provisioning_service.DeleteInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_instance(resp) + return resp + + class _GetInstance(ProvisioningRestStub): + def __hash__(self): + return hash("GetInstance") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: provisioning_service.GetInstanceRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> provisioning_service.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.provisioning_service.GetInstanceRequest): + The request object. Request message for GetInstance. + 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: + ~.provisioning_service.Instance: + An Instance represents the instance + resources of the Registry. Currently, + only one instance is allowed for each + project. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/instances/*}', + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = provisioning_service.GetInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = provisioning_service.Instance() + pb_resp = provisioning_service.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + @property + def create_instance(self) -> Callable[ + [provisioning_service.CreateInstanceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_instance(self) -> Callable[ + [provisioning_service.DeleteInstanceRequest], + operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance(self) -> Callable[ + [provisioning_service.GetInstanceRequest], + provisioning_service.Instance]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(ProvisioningRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object 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: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(ProvisioningRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object 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: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(ProvisioningRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/runtime}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(ProvisioningRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/runtime}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request['body'])) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(ProvisioningRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/runtime}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request['body'])) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(ProvisioningRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request['body'])) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(ProvisioningRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(ProvisioningRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object 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: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(ProvisioningRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object 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 from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'ProvisioningRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py new file mode 100644 index 0000000..d21b3d3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py @@ -0,0 +1,22 @@ +# -*- 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. +# +from .client import RegistryClient +from .async_client import RegistryAsyncClient + +__all__ = ( + 'RegistryClient', + 'RegistryAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py new file mode 100644 index 0000000..80509c2 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py @@ -0,0 +1,4984 @@ +# -*- 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. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.apigee_registry_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.apigee_registry_v1.services.registry import pagers +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service +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 any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import RegistryTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegistryGrpcAsyncIOTransport +from .client import RegistryClient + + +class RegistryAsyncClient: + """The Registry service allows teams to manage descriptions of + APIs. + """ + + _client: RegistryClient + + DEFAULT_ENDPOINT = RegistryClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegistryClient.DEFAULT_MTLS_ENDPOINT + + api_path = staticmethod(RegistryClient.api_path) + parse_api_path = staticmethod(RegistryClient.parse_api_path) + api_deployment_path = staticmethod(RegistryClient.api_deployment_path) + parse_api_deployment_path = staticmethod(RegistryClient.parse_api_deployment_path) + api_spec_path = staticmethod(RegistryClient.api_spec_path) + parse_api_spec_path = staticmethod(RegistryClient.parse_api_spec_path) + api_version_path = staticmethod(RegistryClient.api_version_path) + parse_api_version_path = staticmethod(RegistryClient.parse_api_version_path) + artifact_path = staticmethod(RegistryClient.artifact_path) + parse_artifact_path = staticmethod(RegistryClient.parse_artifact_path) + common_billing_account_path = staticmethod(RegistryClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(RegistryClient.parse_common_billing_account_path) + common_folder_path = staticmethod(RegistryClient.common_folder_path) + parse_common_folder_path = staticmethod(RegistryClient.parse_common_folder_path) + common_organization_path = staticmethod(RegistryClient.common_organization_path) + parse_common_organization_path = staticmethod(RegistryClient.parse_common_organization_path) + common_project_path = staticmethod(RegistryClient.common_project_path) + parse_common_project_path = staticmethod(RegistryClient.parse_common_project_path) + common_location_path = staticmethod(RegistryClient.common_location_path) + parse_common_location_path = staticmethod(RegistryClient.parse_common_location_path) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegistryAsyncClient: The constructed client. + """ + return RegistryClient.from_service_account_info.__func__(RegistryAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegistryAsyncClient: The constructed client. + """ + return RegistryClient.from_service_account_file.__func__(RegistryAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + 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 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. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RegistryClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RegistryTransport: + """Returns the transport used by the client instance. + + Returns: + RegistryTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(RegistryClient).get_transport_class, type(RegistryClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, RegistryTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the registry client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RegistryTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RegistryClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_apis(self, + request: Optional[Union[registry_service.ListApisRequest, 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.ListApisAsyncPager: + r"""Returns matching APIs. + + .. 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 apigee_registry_v1 + + async def sample_list_apis(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApisRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apis(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApisRequest, dict]]): + The request object. Request message for ListApis. + parent (:class:`str`): + Required. The parent, which owns this collection of + APIs. Format: ``projects/*/locations/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApisAsyncPager: + Response message for ListApis. + 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 = registry_service.ListApisRequest(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_apis, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListApisAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_api(self, + request: Optional[Union[registry_service.GetApiRequest, 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]] = (), + ) -> registry_models.Api: + r"""Returns a specified API. + + .. 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 apigee_registry_v1 + + async def sample_get_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiRequest, dict]]): + The request object. Request message for GetApi. + name (:class:`str`): + Required. The name of the API to retrieve. Format: + ``projects/*/locations/*/apis/*`` + + 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.apigee_registry_v1.types.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + # 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 = registry_service.GetApiRequest(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_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_api(self, + request: Optional[Union[registry_service.CreateApiRequest, dict]] = None, + *, + parent: Optional[str] = None, + api: Optional[registry_models.Api] = None, + api_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Api: + r"""Creates a specified API. + + .. 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 apigee_registry_v1 + + async def sample_create_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiRequest( + parent="parent_value", + api_id="api_id_value", + ) + + # Make the request + response = await client.create_api(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiRequest, dict]]): + The request object. Request message for CreateApi. + parent (:class:`str`): + Required. The parent, which owns this collection of + APIs. Format: ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api (:class:`google.cloud.apigee_registry_v1.types.Api`): + Required. The API to create. + This corresponds to the ``api`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_id (:class:`str`): + Required. The ID to use for the API, which will become + the final component of the API's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + # 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, api, api_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.CreateApiRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api is not None: + request.api = api + if api_id is not None: + request.api_id = api_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_api(self, + request: Optional[Union[registry_service.UpdateApiRequest, dict]] = None, + *, + api: Optional[registry_models.Api] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Api: + r"""Used to modify a specified API. + + .. 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 apigee_registry_v1 + + async def sample_update_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiRequest( + ) + + # Make the request + response = await client.update_api(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiRequest, dict]]): + The request object. Request message for UpdateApi. + api (:class:`google.cloud.apigee_registry_v1.types.Api`): + Required. The API to update. + + The ``name`` field is used to identify the API to + update. Format: ``projects/*/locations/*/apis/*`` + + This corresponds to the ``api`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + # 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([api, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.UpdateApiRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api is not None: + request.api = api + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api.name", request.api.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_api(self, + request: Optional[Union[registry_service.DeleteApiRequest, 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]] = (), + ) -> None: + r"""Removes a specified API and all of the resources that + it owns. + + .. 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 apigee_registry_v1 + + async def sample_delete_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiRequest( + name="name_value", + ) + + # Make the request + await client.delete_api(request=request) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiRequest, dict]]): + The request object. Request message for DeleteApi. + name (:class:`str`): + Required. The name of the API to delete. Format: + ``projects/*/locations/*/apis/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = registry_service.DeleteApiRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_api_versions(self, + request: Optional[Union[registry_service.ListApiVersionsRequest, 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.ListApiVersionsAsyncPager: + r"""Returns matching versions. + + .. 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 apigee_registry_v1 + + async def sample_list_api_versions(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiVersionsRequest, dict]]): + The request object. Request message for ListApiVersions. + parent (:class:`str`): + Required. The parent, which owns this collection of + versions. Format: ``projects/*/locations/*/apis/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApiVersionsAsyncPager: + Response message for ListApiVersions. + 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 = registry_service.ListApiVersionsRequest(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_api_versions, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListApiVersionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_api_version(self, + request: Optional[Union[registry_service.GetApiVersionRequest, 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]] = (), + ) -> registry_models.ApiVersion: + r"""Returns a specified version. + + .. 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 apigee_registry_v1 + + async def sample_get_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiVersionRequest, dict]]): + The request object. Request message for GetApiVersion. + name (:class:`str`): + Required. The name of the version to retrieve. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + 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.apigee_registry_v1.types.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + # 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 = registry_service.GetApiVersionRequest(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_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_api_version(self, + request: Optional[Union[registry_service.CreateApiVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + api_version: Optional[registry_models.ApiVersion] = None, + api_version_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiVersion: + r"""Creates a specified version. + + .. 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 apigee_registry_v1 + + async def sample_create_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiVersionRequest( + parent="parent_value", + api_version_id="api_version_id_value", + ) + + # Make the request + response = await client.create_api_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiVersionRequest, dict]]): + The request object. Request message for + CreateApiVersion. + parent (:class:`str`): + Required. The parent, which owns this collection of + versions. Format: ``projects/*/locations/*/apis/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_version (:class:`google.cloud.apigee_registry_v1.types.ApiVersion`): + Required. The version to create. + This corresponds to the ``api_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_version_id (:class:`str`): + Required. The ID to use for the version, which will + become the final component of the version's resource + name. + + This value should be 1-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_version_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + # 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, api_version, api_version_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.CreateApiVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api_version is not None: + request.api_version = api_version + if api_version_id is not None: + request.api_version_id = api_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_api_version(self, + request: Optional[Union[registry_service.UpdateApiVersionRequest, dict]] = None, + *, + api_version: Optional[registry_models.ApiVersion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiVersion: + r"""Used to modify a specified version. + + .. 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 apigee_registry_v1 + + async def sample_update_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiVersionRequest( + ) + + # Make the request + response = await client.update_api_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest, dict]]): + The request object. Request message for + UpdateApiVersion. + api_version (:class:`google.cloud.apigee_registry_v1.types.ApiVersion`): + Required. The version to update. + + The ``name`` field is used to identify the version to + update. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + This corresponds to the ``api_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + # 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([api_version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.UpdateApiVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api_version is not None: + request.api_version = api_version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api_version.name", request.api_version.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_api_version(self, + request: Optional[Union[registry_service.DeleteApiVersionRequest, 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]] = (), + ) -> None: + r"""Removes a specified version and all of the resources + that it owns. + + .. 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 apigee_registry_v1 + + async def sample_delete_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_api_version(request=request) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest, dict]]): + The request object. Request message for + DeleteApiVersion. + name (:class:`str`): + Required. The name of the version to delete. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = registry_service.DeleteApiVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_api_specs(self, + request: Optional[Union[registry_service.ListApiSpecsRequest, 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.ListApiSpecsAsyncPager: + r"""Returns matching specs. + + .. 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 apigee_registry_v1 + + async def sample_list_api_specs(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_specs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiSpecsRequest, dict]]): + The request object. Request message for ListApiSpecs. + parent (:class:`str`): + Required. The parent, which owns this collection of + specs. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApiSpecsAsyncPager: + Response message for ListApiSpecs. + 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 = registry_service.ListApiSpecsRequest(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_api_specs, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListApiSpecsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_api_spec(self, + request: Optional[Union[registry_service.GetApiSpecRequest, 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]] = (), + ) -> registry_models.ApiSpec: + r"""Returns a specified spec. + + .. 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 apigee_registry_v1 + + async def sample_get_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiSpecRequest, dict]]): + The request object. Request message for GetApiSpec. + name (:class:`str`): + Required. The name of the spec to retrieve. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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 = registry_service.GetApiSpecRequest(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_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("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_api_spec_contents(self, + request: Optional[Union[registry_service.GetApiSpecContentsRequest, 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]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Returns the contents of a specified spec. If specs are stored + with GZip compression, the default behavior is to return the + spec uncompressed (the mime_type response field indicates the + exact format returned). + + .. 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 apigee_registry_v1 + + async def sample_get_api_spec_contents(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecContentsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_spec_contents(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest, dict]]): + The request object. Request message for + GetApiSpecContents. + name (:class:`str`): + Required. The name of the spec whose contents should be + retrieved. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # 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 = registry_service.GetApiSpecContentsRequest(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_api_spec_contents, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_api_spec(self, + request: Optional[Union[registry_service.CreateApiSpecRequest, dict]] = None, + *, + parent: Optional[str] = None, + api_spec: Optional[registry_models.ApiSpec] = None, + api_spec_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Creates a specified spec. + + .. 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 apigee_registry_v1 + + async def sample_create_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiSpecRequest( + parent="parent_value", + api_spec_id="api_spec_id_value", + ) + + # Make the request + response = await client.create_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiSpecRequest, dict]]): + The request object. Request message for CreateApiSpec. + parent (:class:`str`): + Required. The parent, which owns this collection of + specs. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_spec (:class:`google.cloud.apigee_registry_v1.types.ApiSpec`): + Required. The spec to create. + This corresponds to the ``api_spec`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_spec_id (:class:`str`): + Required. The ID to use for the spec, which will become + the final component of the spec's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_spec_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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, api_spec, api_spec_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.CreateApiSpecRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api_spec is not None: + request.api_spec = api_spec + if api_spec_id is not None: + request.api_spec_id = api_spec_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_api_spec(self, + request: Optional[Union[registry_service.UpdateApiSpecRequest, dict]] = None, + *, + api_spec: Optional[registry_models.ApiSpec] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Used to modify a specified spec. + + .. 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 apigee_registry_v1 + + async def sample_update_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiSpecRequest( + ) + + # Make the request + response = await client.update_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest, dict]]): + The request object. Request message for UpdateApiSpec. + api_spec (:class:`google.cloud.apigee_registry_v1.types.ApiSpec`): + Required. The spec to update. + + The ``name`` field is used to identify the spec to + update. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + This corresponds to the ``api_spec`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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([api_spec, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.UpdateApiSpecRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api_spec is not None: + request.api_spec = api_spec + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api_spec.name", request.api_spec.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_api_spec(self, + request: Optional[Union[registry_service.DeleteApiSpecRequest, 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]] = (), + ) -> None: + r"""Removes a specified spec, all revisions, and all + child resources (e.g., artifacts). + + .. 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 apigee_registry_v1 + + async def sample_delete_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRequest( + name="name_value", + ) + + # Make the request + await client.delete_api_spec(request=request) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest, dict]]): + The request object. Request message for DeleteApiSpec. + name (:class:`str`): + Required. The name of the spec to delete. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = registry_service.DeleteApiSpecRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def tag_api_spec_revision(self, + request: Optional[Union[registry_service.TagApiSpecRevisionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Adds a tag to a specified revision of a spec. + + .. 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 apigee_registry_v1 + + async def sample_tag_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiSpecRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = await client.tag_api_spec_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest, dict]]): + The request object. Request message for + TagApiSpecRevision. + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # Create or coerce a protobuf request object. + request = registry_service.TagApiSpecRevisionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.tag_api_spec_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("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_api_spec_revisions(self, + request: Optional[Union[registry_service.ListApiSpecRevisionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApiSpecRevisionsAsyncPager: + r"""Lists all revisions of a spec. + Revisions are returned in descending order of revision + creation time. + + .. 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 apigee_registry_v1 + + async def sample_list_api_spec_revisions(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_spec_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest, dict]]): + The request object. Request message for + ListApiSpecRevisions. + 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.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsAsyncPager: + Response message for + ListApiSpecRevisionsResponse. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = registry_service.ListApiSpecRevisionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_api_spec_revisions, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListApiSpecRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def rollback_api_spec(self, + request: Optional[Union[registry_service.RollbackApiSpecRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + .. 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 apigee_registry_v1 + + async def sample_rollback_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiSpecRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = await client.rollback_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest, dict]]): + The request object. Request message for RollbackApiSpec. + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # Create or coerce a protobuf request object. + request = registry_service.RollbackApiSpecRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.rollback_api_spec, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_api_spec_revision(self, + request: Optional[Union[registry_service.DeleteApiSpecRevisionRequest, 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]] = (), + ) -> registry_models.ApiSpec: + r"""Deletes a revision of a spec. + + .. 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 apigee_registry_v1 + + async def sample_delete_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_api_spec_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest, dict]]): + The request object. Request message for + DeleteApiSpecRevision. + name (:class:`str`): + Required. The name of the spec revision to be deleted, + with a revision ID explicitly included. + + Example: + ``projects/sample/locations/global/apis/petstore/versions/1.0.0/specs/openapi.yaml@c7cfa2a8`` + + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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 = registry_service.DeleteApiSpecRevisionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_api_spec_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("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_api_deployments(self, + request: Optional[Union[registry_service.ListApiDeploymentsRequest, 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.ListApiDeploymentsAsyncPager: + r"""Returns matching deployments. + + .. 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 apigee_registry_v1 + + async def sample_list_api_deployments(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest, dict]]): + The request object. Request message for + ListApiDeployments. + parent (:class:`str`): + Required. The parent, which owns this collection of + deployments. Format: ``projects/*/locations/*/apis/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsAsyncPager: + Response message for + ListApiDeployments. + 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 = registry_service.ListApiDeploymentsRequest(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_api_deployments, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListApiDeploymentsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_api_deployment(self, + request: Optional[Union[registry_service.GetApiDeploymentRequest, 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]] = (), + ) -> registry_models.ApiDeployment: + r"""Returns a specified deployment. + + .. 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 apigee_registry_v1 + + async def sample_get_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest, dict]]): + The request object. Request message for + GetApiDeployment. + name (:class:`str`): + Required. The name of the deployment to retrieve. + Format: ``projects/*/locations/*/apis/*/deployments/*`` + + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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 = registry_service.GetApiDeploymentRequest(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_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_api_deployment(self, + request: Optional[Union[registry_service.CreateApiDeploymentRequest, dict]] = None, + *, + parent: Optional[str] = None, + api_deployment: Optional[registry_models.ApiDeployment] = None, + api_deployment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Creates a specified deployment. + + .. 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 apigee_registry_v1 + + async def sample_create_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiDeploymentRequest( + parent="parent_value", + api_deployment_id="api_deployment_id_value", + ) + + # Make the request + response = await client.create_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest, dict]]): + The request object. Request message for + CreateApiDeployment. + parent (:class:`str`): + Required. The parent, which owns this collection of + deployments. Format: ``projects/*/locations/*/apis/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_deployment (:class:`google.cloud.apigee_registry_v1.types.ApiDeployment`): + Required. The deployment to create. + This corresponds to the ``api_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_deployment_id (:class:`str`): + Required. The ID to use for the deployment, which will + become the final component of the deployment's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_deployment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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, api_deployment, api_deployment_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.CreateApiDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api_deployment is not None: + request.api_deployment = api_deployment + if api_deployment_id is not None: + request.api_deployment_id = api_deployment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_api_deployment(self, + request: Optional[Union[registry_service.UpdateApiDeploymentRequest, dict]] = None, + *, + api_deployment: Optional[registry_models.ApiDeployment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Used to modify a specified deployment. + + .. 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 apigee_registry_v1 + + async def sample_update_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiDeploymentRequest( + ) + + # Make the request + response = await client.update_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest, dict]]): + The request object. Request message for + UpdateApiDeployment. + api_deployment (:class:`google.cloud.apigee_registry_v1.types.ApiDeployment`): + Required. The deployment to update. + + The ``name`` field is used to identify the deployment to + update. Format: + ``projects/*/locations/*/apis/*/deployments/*`` + + This corresponds to the ``api_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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([api_deployment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.UpdateApiDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api_deployment is not None: + request.api_deployment = api_deployment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api_deployment.name", request.api_deployment.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_api_deployment(self, + request: Optional[Union[registry_service.DeleteApiDeploymentRequest, 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]] = (), + ) -> None: + r"""Removes a specified deployment, all revisions, and + all child resources (e.g., artifacts). + + .. 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 apigee_registry_v1 + + async def sample_delete_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRequest( + name="name_value", + ) + + # Make the request + await client.delete_api_deployment(request=request) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest, dict]]): + The request object. Request message for + DeleteApiDeployment. + name (:class:`str`): + Required. The name of the deployment to delete. Format: + ``projects/*/locations/*/apis/*/deployments/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = registry_service.DeleteApiDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def tag_api_deployment_revision(self, + request: Optional[Union[registry_service.TagApiDeploymentRevisionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Adds a tag to a specified revision of a + deployment. + + .. 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 apigee_registry_v1 + + async def sample_tag_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiDeploymentRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = await client.tag_api_deployment_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest, dict]]): + The request object. Request message for + TagApiDeploymentRevision. + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # Create or coerce a protobuf request object. + request = registry_service.TagApiDeploymentRevisionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.tag_api_deployment_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("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_api_deployment_revisions(self, + request: Optional[Union[registry_service.ListApiDeploymentRevisionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApiDeploymentRevisionsAsyncPager: + r"""Lists all revisions of a deployment. + Revisions are returned in descending order of revision + creation time. + + .. 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 apigee_registry_v1 + + async def sample_list_api_deployment_revisions(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_deployment_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest, dict]]): + The request object. Request message for + ListApiDeploymentRevisions. + 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsAsyncPager: + Response message for + ListApiDeploymentRevisionsResponse. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + request = registry_service.ListApiDeploymentRevisionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_api_deployment_revisions, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListApiDeploymentRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def rollback_api_deployment(self, + request: Optional[Union[registry_service.RollbackApiDeploymentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + .. 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 apigee_registry_v1 + + async def sample_rollback_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiDeploymentRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = await client.rollback_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest, dict]]): + The request object. Request message for + RollbackApiDeployment. + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # Create or coerce a protobuf request object. + request = registry_service.RollbackApiDeploymentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.rollback_api_deployment, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_api_deployment_revision(self, + request: Optional[Union[registry_service.DeleteApiDeploymentRevisionRequest, 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]] = (), + ) -> registry_models.ApiDeployment: + r"""Deletes a revision of a deployment. + + .. 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 apigee_registry_v1 + + async def sample_delete_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_api_deployment_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest, dict]]): + The request object. Request message for + DeleteApiDeploymentRevision. + name (:class:`str`): + Required. The name of the deployment revision to be + deleted, with a revision ID explicitly included. + + Example: + ``projects/sample/locations/global/apis/petstore/deployments/prod@c7cfa2a8`` + + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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 = registry_service.DeleteApiDeploymentRevisionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_api_deployment_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("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_artifacts(self, + request: Optional[Union[registry_service.ListArtifactsRequest, 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.ListArtifactsAsyncPager: + r"""Returns matching artifacts. + + .. 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 apigee_registry_v1 + + async def sample_list_artifacts(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListArtifactsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_artifacts(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ListArtifactsRequest, dict]]): + The request object. Request message for ListArtifacts. + parent (:class:`str`): + Required. The parent, which owns this collection of + artifacts. Format: ``{parent}`` + + 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.apigee_registry_v1.services.registry.pagers.ListArtifactsAsyncPager: + Response message for ListArtifacts. + 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 = registry_service.ListArtifactsRequest(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_artifacts, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListArtifactsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_artifact(self, + request: Optional[Union[registry_service.GetArtifactRequest, 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]] = (), + ) -> registry_models.Artifact: + r"""Returns a specified artifact. + + .. 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 apigee_registry_v1 + + async def sample_get_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactRequest( + name="name_value", + ) + + # Make the request + response = await client.get_artifact(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetArtifactRequest, dict]]): + The request object. Request message for GetArtifact. + name (:class:`str`): + Required. The name of the artifact to retrieve. Format: + ``{parent}/artifacts/*`` + + 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.apigee_registry_v1.types.Artifact: + Artifacts of resources. Artifacts are unique (single-value) per resource + and are used to store metadata that is too large or + numerous to be stored directly on the resource. Since + artifacts are stored separately from parent + resources, they should generally be used for metadata + that is needed infrequently, i.e., not for display in + primary views of the resource but perhaps displayed + or downloaded upon request. The ListArtifacts method + allows artifacts to be quickly enumerated and checked + for presence without downloading their + (potentially-large) contents. + + """ + # 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 = registry_service.GetArtifactRequest(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_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("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_artifact_contents(self, + request: Optional[Union[registry_service.GetArtifactContentsRequest, 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]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Returns the contents of a specified artifact. If artifacts are + stored with GZip compression, the default behavior is to return + the artifact uncompressed (the mime_type response field + indicates the exact format returned). + + .. 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 apigee_registry_v1 + + async def sample_get_artifact_contents(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactContentsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_artifact_contents(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest, dict]]): + The request object. Request message for + GetArtifactContents. + name (:class:`str`): + Required. The name of the artifact whose contents should + be retrieved. Format: ``{parent}/artifacts/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # 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 = registry_service.GetArtifactContentsRequest(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_artifact_contents, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_artifact(self, + request: Optional[Union[registry_service.CreateArtifactRequest, dict]] = None, + *, + parent: Optional[str] = None, + artifact: Optional[registry_models.Artifact] = None, + artifact_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Artifact: + r"""Creates a specified artifact. + + .. 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 apigee_registry_v1 + + async def sample_create_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateArtifactRequest( + parent="parent_value", + artifact_id="artifact_id_value", + ) + + # Make the request + response = await client.create_artifact(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateArtifactRequest, dict]]): + The request object. Request message for CreateArtifact. + parent (:class:`str`): + Required. The parent, which owns this collection of + artifacts. Format: ``{parent}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + artifact (:class:`google.cloud.apigee_registry_v1.types.Artifact`): + Required. The artifact to create. + This corresponds to the ``artifact`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + artifact_id (:class:`str`): + Required. The ID to use for the artifact, which will + become the final component of the artifact's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``artifact_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.Artifact: + Artifacts of resources. Artifacts are unique (single-value) per resource + and are used to store metadata that is too large or + numerous to be stored directly on the resource. Since + artifacts are stored separately from parent + resources, they should generally be used for metadata + that is needed infrequently, i.e., not for display in + primary views of the resource but perhaps displayed + or downloaded upon request. The ListArtifacts method + allows artifacts to be quickly enumerated and checked + for presence without downloading their + (potentially-large) contents. + + """ + # 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, artifact, artifact_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + request = registry_service.CreateArtifactRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if artifact is not None: + request.artifact = artifact + if artifact_id is not None: + request.artifact_id = artifact_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def replace_artifact(self, + request: Optional[Union[registry_service.ReplaceArtifactRequest, dict]] = None, + *, + artifact: Optional[registry_models.Artifact] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Artifact: + r"""Used to replace a specified artifact. + + .. 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 apigee_registry_v1 + + async def sample_replace_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ReplaceArtifactRequest( + ) + + # Make the request + response = await client.replace_artifact(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest, dict]]): + The request object. Request message for ReplaceArtifact. + artifact (:class:`google.cloud.apigee_registry_v1.types.Artifact`): + Required. The artifact to replace. + + The ``name`` field is used to identify the artifact to + replace. Format: ``{parent}/artifacts/*`` + + This corresponds to the ``artifact`` 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.apigee_registry_v1.types.Artifact: + Artifacts of resources. Artifacts are unique (single-value) per resource + and are used to store metadata that is too large or + numerous to be stored directly on the resource. Since + artifacts are stored separately from parent + resources, they should generally be used for metadata + that is needed infrequently, i.e., not for display in + primary views of the resource but perhaps displayed + or downloaded upon request. The ListArtifacts method + allows artifacts to be quickly enumerated and checked + for presence without downloading their + (potentially-large) contents. + + """ + # 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([artifact]) + 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 = registry_service.ReplaceArtifactRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if artifact is not None: + request.artifact = artifact + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.replace_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("artifact.name", request.artifact.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_artifact(self, + request: Optional[Union[registry_service.DeleteArtifactRequest, 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]] = (), + ) -> None: + r"""Removes a specified artifact. + + .. 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 apigee_registry_v1 + + async def sample_delete_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteArtifactRequest( + name="name_value", + ) + + # Make the request + await client.delete_artifact(request=request) + + Args: + request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteArtifactRequest, dict]]): + The request object. Request message for DeleteArtifact. + name (:class:`str`): + Required. The name of the artifact to delete. Format: + ``{parent}/artifacts/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 = registry_service.DeleteArtifactRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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 + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "RegistryAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py new file mode 100644 index 0000000..c6ad584 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py @@ -0,0 +1,4928 @@ +# -*- 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. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.apigee_registry_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.apigee_registry_v1.services.registry import pagers +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service +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 any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import RegistryTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegistryGrpcTransport +from .transports.grpc_asyncio import RegistryGrpcAsyncIOTransport +from .transports.rest import RegistryRestTransport + + +class RegistryClientMeta(type): + """Metaclass for the Registry client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + _transport_registry = OrderedDict() # type: Dict[str, Type[RegistryTransport]] + _transport_registry["grpc"] = RegistryGrpcTransport + _transport_registry["grpc_asyncio"] = RegistryGrpcAsyncIOTransport + _transport_registry["rest"] = RegistryRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[RegistryTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RegistryClient(metaclass=RegistryClientMeta): + """The Registry service allows teams to manage descriptions of + APIs. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "apigeeregistry.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegistryClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RegistryClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file( + filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegistryTransport: + """Returns the transport used by the client instance. + + Returns: + RegistryTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def api_path(project: str,location: str,api: str,) -> str: + """Returns a fully-qualified api string.""" + return "projects/{project}/locations/{location}/apis/{api}".format(project=project, location=location, api=api, ) + + @staticmethod + def parse_api_path(path: str) -> Dict[str,str]: + """Parses a api path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def api_deployment_path(project: str,location: str,api: str,deployment: str,) -> str: + """Returns a fully-qualified api_deployment string.""" + return "projects/{project}/locations/{location}/apis/{api}/deployments/{deployment}".format(project=project, location=location, api=api, deployment=deployment, ) + + @staticmethod + def parse_api_deployment_path(path: str) -> Dict[str,str]: + """Parses a api_deployment path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)/deployments/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def api_spec_path(project: str,location: str,api: str,version: str,spec: str,) -> str: + """Returns a fully-qualified api_spec string.""" + return "projects/{project}/locations/{location}/apis/{api}/versions/{version}/specs/{spec}".format(project=project, location=location, api=api, version=version, spec=spec, ) + + @staticmethod + def parse_api_spec_path(path: str) -> Dict[str,str]: + """Parses a api_spec path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)/versions/(?P.+?)/specs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def api_version_path(project: str,location: str,api: str,version: str,) -> str: + """Returns a fully-qualified api_version string.""" + return "projects/{project}/locations/{location}/apis/{api}/versions/{version}".format(project=project, location=location, api=api, version=version, ) + + @staticmethod + def parse_api_version_path(path: str) -> Dict[str,str]: + """Parses a api_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)/versions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def artifact_path(project: str,location: str,artifact: str,) -> str: + """Returns a fully-qualified artifact string.""" + return "projects/{project}/locations/{location}/artifacts/{artifact}".format(project=project, location=location, artifact=artifact, ) + + @staticmethod + def parse_artifact_path(path: str) -> Dict[str,str]: + """Parses a artifact path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/artifacts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + 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 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. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, RegistryTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the registry client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, RegistryTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) + + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RegistryTransport): + # transport is a RegistryTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_apis(self, + request: Optional[Union[registry_service.ListApisRequest, 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.ListApisPager: + r"""Returns matching APIs. + + .. 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 apigee_registry_v1 + + def sample_list_apis(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApisRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apis(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ListApisRequest, dict]): + The request object. Request message for ListApis. + parent (str): + Required. The parent, which owns this collection of + APIs. Format: ``projects/*/locations/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApisPager: + Response message for ListApis. + 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 registry_service.ListApisRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ListApisRequest): + request = registry_service.ListApisRequest(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_apis] + + # 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.ListApisPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_api(self, + request: Optional[Union[registry_service.GetApiRequest, 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]] = (), + ) -> registry_models.Api: + r"""Returns a specified API. + + .. 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 apigee_registry_v1 + + def sample_get_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiRequest( + name="name_value", + ) + + # Make the request + response = client.get_api(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetApiRequest, dict]): + The request object. Request message for GetApi. + name (str): + Required. The name of the API to retrieve. Format: + ``projects/*/locations/*/apis/*`` + + 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.apigee_registry_v1.types.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + # 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 registry_service.GetApiRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.GetApiRequest): + request = registry_service.GetApiRequest(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_api] + + # 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 create_api(self, + request: Optional[Union[registry_service.CreateApiRequest, dict]] = None, + *, + parent: Optional[str] = None, + api: Optional[registry_models.Api] = None, + api_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Api: + r"""Creates a specified API. + + .. 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 apigee_registry_v1 + + def sample_create_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiRequest( + parent="parent_value", + api_id="api_id_value", + ) + + # Make the request + response = client.create_api(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.CreateApiRequest, dict]): + The request object. Request message for CreateApi. + parent (str): + Required. The parent, which owns this collection of + APIs. Format: ``projects/*/locations/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api (google.cloud.apigee_registry_v1.types.Api): + Required. The API to create. + This corresponds to the ``api`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_id (str): + Required. The ID to use for the API, which will become + the final component of the API's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + # 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, api, api_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.CreateApiRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.CreateApiRequest): + request = registry_service.CreateApiRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api is not None: + request.api = api + if api_id is not None: + request.api_id = api_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_api] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_api(self, + request: Optional[Union[registry_service.UpdateApiRequest, dict]] = None, + *, + api: Optional[registry_models.Api] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Api: + r"""Used to modify a specified API. + + .. 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 apigee_registry_v1 + + def sample_update_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiRequest( + ) + + # Make the request + response = client.update_api(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.UpdateApiRequest, dict]): + The request object. Request message for UpdateApi. + api (google.cloud.apigee_registry_v1.types.Api): + Required. The API to update. + + The ``name`` field is used to identify the API to + update. Format: ``projects/*/locations/*/apis/*`` + + This corresponds to the ``api`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + # 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([api, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.UpdateApiRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.UpdateApiRequest): + request = registry_service.UpdateApiRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api is not None: + request.api = api + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_api] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api.name", request.api.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_api(self, + request: Optional[Union[registry_service.DeleteApiRequest, 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]] = (), + ) -> None: + r"""Removes a specified API and all of the resources that + it owns. + + .. 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 apigee_registry_v1 + + def sample_delete_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiRequest( + name="name_value", + ) + + # Make the request + client.delete_api(request=request) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteApiRequest, dict]): + The request object. Request message for DeleteApi. + name (str): + Required. The name of the API to delete. Format: + ``projects/*/locations/*/apis/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 registry_service.DeleteApiRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.DeleteApiRequest): + request = registry_service.DeleteApiRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_api] + + # 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 list_api_versions(self, + request: Optional[Union[registry_service.ListApiVersionsRequest, 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.ListApiVersionsPager: + r"""Returns matching versions. + + .. 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 apigee_registry_v1 + + def sample_list_api_versions(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ListApiVersionsRequest, dict]): + The request object. Request message for ListApiVersions. + parent (str): + Required. The parent, which owns this collection of + versions. Format: ``projects/*/locations/*/apis/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApiVersionsPager: + Response message for ListApiVersions. + 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 registry_service.ListApiVersionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ListApiVersionsRequest): + request = registry_service.ListApiVersionsRequest(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_api_versions] + + # 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.ListApiVersionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_api_version(self, + request: Optional[Union[registry_service.GetApiVersionRequest, 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]] = (), + ) -> registry_models.ApiVersion: + r"""Returns a specified version. + + .. 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 apigee_registry_v1 + + def sample_get_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetApiVersionRequest, dict]): + The request object. Request message for GetApiVersion. + name (str): + Required. The name of the version to retrieve. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + 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.apigee_registry_v1.types.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + # 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 registry_service.GetApiVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.GetApiVersionRequest): + request = registry_service.GetApiVersionRequest(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_api_version] + + # 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 create_api_version(self, + request: Optional[Union[registry_service.CreateApiVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + api_version: Optional[registry_models.ApiVersion] = None, + api_version_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiVersion: + r"""Creates a specified version. + + .. 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 apigee_registry_v1 + + def sample_create_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiVersionRequest( + parent="parent_value", + api_version_id="api_version_id_value", + ) + + # Make the request + response = client.create_api_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.CreateApiVersionRequest, dict]): + The request object. Request message for + CreateApiVersion. + parent (str): + Required. The parent, which owns this collection of + versions. Format: ``projects/*/locations/*/apis/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_version (google.cloud.apigee_registry_v1.types.ApiVersion): + Required. The version to create. + This corresponds to the ``api_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_version_id (str): + Required. The ID to use for the version, which will + become the final component of the version's resource + name. + + This value should be 1-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_version_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + # 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, api_version, api_version_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.CreateApiVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.CreateApiVersionRequest): + request = registry_service.CreateApiVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api_version is not None: + request.api_version = api_version + if api_version_id is not None: + request.api_version_id = api_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_api_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_api_version(self, + request: Optional[Union[registry_service.UpdateApiVersionRequest, dict]] = None, + *, + api_version: Optional[registry_models.ApiVersion] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiVersion: + r"""Used to modify a specified version. + + .. 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 apigee_registry_v1 + + def sample_update_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiVersionRequest( + ) + + # Make the request + response = client.update_api_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest, dict]): + The request object. Request message for + UpdateApiVersion. + api_version (google.cloud.apigee_registry_v1.types.ApiVersion): + Required. The version to update. + + The ``name`` field is used to identify the version to + update. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + This corresponds to the ``api_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + # 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([api_version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.UpdateApiVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.UpdateApiVersionRequest): + request = registry_service.UpdateApiVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api_version is not None: + request.api_version = api_version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_api_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api_version.name", request.api_version.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_api_version(self, + request: Optional[Union[registry_service.DeleteApiVersionRequest, 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]] = (), + ) -> None: + r"""Removes a specified version and all of the resources + that it owns. + + .. 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 apigee_registry_v1 + + def sample_delete_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_api_version(request=request) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest, dict]): + The request object. Request message for + DeleteApiVersion. + name (str): + Required. The name of the version to delete. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 registry_service.DeleteApiVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.DeleteApiVersionRequest): + request = registry_service.DeleteApiVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_api_version] + + # 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 list_api_specs(self, + request: Optional[Union[registry_service.ListApiSpecsRequest, 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.ListApiSpecsPager: + r"""Returns matching specs. + + .. 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 apigee_registry_v1 + + def sample_list_api_specs(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_specs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ListApiSpecsRequest, dict]): + The request object. Request message for ListApiSpecs. + parent (str): + Required. The parent, which owns this collection of + specs. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApiSpecsPager: + Response message for ListApiSpecs. + 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 registry_service.ListApiSpecsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ListApiSpecsRequest): + request = registry_service.ListApiSpecsRequest(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_api_specs] + + # 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.ListApiSpecsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_api_spec(self, + request: Optional[Union[registry_service.GetApiSpecRequest, 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]] = (), + ) -> registry_models.ApiSpec: + r"""Returns a specified spec. + + .. 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 apigee_registry_v1 + + def sample_get_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetApiSpecRequest, dict]): + The request object. Request message for GetApiSpec. + name (str): + Required. The name of the spec to retrieve. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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 registry_service.GetApiSpecRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.GetApiSpecRequest): + request = registry_service.GetApiSpecRequest(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_api_spec] + + # 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_api_spec_contents(self, + request: Optional[Union[registry_service.GetApiSpecContentsRequest, 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]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Returns the contents of a specified spec. If specs are stored + with GZip compression, the default behavior is to return the + spec uncompressed (the mime_type response field indicates the + exact format returned). + + .. 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 apigee_registry_v1 + + def sample_get_api_spec_contents(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecContentsRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_spec_contents(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest, dict]): + The request object. Request message for + GetApiSpecContents. + name (str): + Required. The name of the spec whose contents should be + retrieved. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # 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 registry_service.GetApiSpecContentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.GetApiSpecContentsRequest): + request = registry_service.GetApiSpecContentsRequest(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_api_spec_contents] + + # 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 create_api_spec(self, + request: Optional[Union[registry_service.CreateApiSpecRequest, dict]] = None, + *, + parent: Optional[str] = None, + api_spec: Optional[registry_models.ApiSpec] = None, + api_spec_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Creates a specified spec. + + .. 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 apigee_registry_v1 + + def sample_create_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiSpecRequest( + parent="parent_value", + api_spec_id="api_spec_id_value", + ) + + # Make the request + response = client.create_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.CreateApiSpecRequest, dict]): + The request object. Request message for CreateApiSpec. + parent (str): + Required. The parent, which owns this collection of + specs. Format: + ``projects/*/locations/*/apis/*/versions/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): + Required. The spec to create. + This corresponds to the ``api_spec`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_spec_id (str): + Required. The ID to use for the spec, which will become + the final component of the spec's resource name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_spec_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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, api_spec, api_spec_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.CreateApiSpecRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.CreateApiSpecRequest): + request = registry_service.CreateApiSpecRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api_spec is not None: + request.api_spec = api_spec + if api_spec_id is not None: + request.api_spec_id = api_spec_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_api_spec] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_api_spec(self, + request: Optional[Union[registry_service.UpdateApiSpecRequest, dict]] = None, + *, + api_spec: Optional[registry_models.ApiSpec] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Used to modify a specified spec. + + .. 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 apigee_registry_v1 + + def sample_update_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiSpecRequest( + ) + + # Make the request + response = client.update_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest, dict]): + The request object. Request message for UpdateApiSpec. + api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): + Required. The spec to update. + + The ``name`` field is used to identify the spec to + update. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + This corresponds to the ``api_spec`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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([api_spec, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.UpdateApiSpecRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.UpdateApiSpecRequest): + request = registry_service.UpdateApiSpecRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api_spec is not None: + request.api_spec = api_spec + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_api_spec] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api_spec.name", request.api_spec.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_api_spec(self, + request: Optional[Union[registry_service.DeleteApiSpecRequest, 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]] = (), + ) -> None: + r"""Removes a specified spec, all revisions, and all + child resources (e.g., artifacts). + + .. 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 apigee_registry_v1 + + def sample_delete_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRequest( + name="name_value", + ) + + # Make the request + client.delete_api_spec(request=request) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest, dict]): + The request object. Request message for DeleteApiSpec. + name (str): + Required. The name of the spec to delete. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 registry_service.DeleteApiSpecRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.DeleteApiSpecRequest): + request = registry_service.DeleteApiSpecRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_api_spec] + + # 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 tag_api_spec_revision(self, + request: Optional[Union[registry_service.TagApiSpecRevisionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Adds a tag to a specified revision of a spec. + + .. 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 apigee_registry_v1 + + def sample_tag_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiSpecRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = client.tag_api_spec_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest, dict]): + The request object. Request message for + TagApiSpecRevision. + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.TagApiSpecRevisionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.TagApiSpecRevisionRequest): + request = registry_service.TagApiSpecRevisionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.tag_api_spec_revision] + + # 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_api_spec_revisions(self, + request: Optional[Union[registry_service.ListApiSpecRevisionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApiSpecRevisionsPager: + r"""Lists all revisions of a spec. + Revisions are returned in descending order of revision + creation time. + + .. 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 apigee_registry_v1 + + def sample_list_api_spec_revisions(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_spec_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest, dict]): + The request object. Request message for + ListApiSpecRevisions. + 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.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsPager: + Response message for + ListApiSpecRevisionsResponse. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.ListApiSpecRevisionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ListApiSpecRevisionsRequest): + request = registry_service.ListApiSpecRevisionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_api_spec_revisions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListApiSpecRevisionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def rollback_api_spec(self, + request: Optional[Union[registry_service.RollbackApiSpecRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiSpec: + r"""Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + .. 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 apigee_registry_v1 + + def sample_rollback_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiSpecRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = client.rollback_api_spec(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest, dict]): + The request object. Request message for RollbackApiSpec. + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.RollbackApiSpecRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.RollbackApiSpecRequest): + request = registry_service.RollbackApiSpecRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rollback_api_spec] + + # 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_api_spec_revision(self, + request: Optional[Union[registry_service.DeleteApiSpecRevisionRequest, 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]] = (), + ) -> registry_models.ApiSpec: + r"""Deletes a revision of a spec. + + .. 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 apigee_registry_v1 + + def sample_delete_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_api_spec_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest, dict]): + The request object. Request message for + DeleteApiSpecRevision. + name (str): + Required. The name of the spec revision to be deleted, + with a revision ID explicitly included. + + Example: + ``projects/sample/locations/global/apis/petstore/versions/1.0.0/specs/openapi.yaml@c7cfa2a8`` + + 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.apigee_registry_v1.types.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + # 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 registry_service.DeleteApiSpecRevisionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.DeleteApiSpecRevisionRequest): + request = registry_service.DeleteApiSpecRevisionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_api_spec_revision] + + # 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_api_deployments(self, + request: Optional[Union[registry_service.ListApiDeploymentsRequest, 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.ListApiDeploymentsPager: + r"""Returns matching deployments. + + .. 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 apigee_registry_v1 + + def sample_list_api_deployments(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest, dict]): + The request object. Request message for + ListApiDeployments. + parent (str): + Required. The parent, which owns this collection of + deployments. Format: ``projects/*/locations/*/apis/*`` + + 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsPager: + Response message for + ListApiDeployments. + 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 registry_service.ListApiDeploymentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ListApiDeploymentsRequest): + request = registry_service.ListApiDeploymentsRequest(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_api_deployments] + + # 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.ListApiDeploymentsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_api_deployment(self, + request: Optional[Union[registry_service.GetApiDeploymentRequest, 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]] = (), + ) -> registry_models.ApiDeployment: + r"""Returns a specified deployment. + + .. 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 apigee_registry_v1 + + def sample_get_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest, dict]): + The request object. Request message for + GetApiDeployment. + name (str): + Required. The name of the deployment to retrieve. + Format: ``projects/*/locations/*/apis/*/deployments/*`` + + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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 registry_service.GetApiDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.GetApiDeploymentRequest): + request = registry_service.GetApiDeploymentRequest(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_api_deployment] + + # 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 create_api_deployment(self, + request: Optional[Union[registry_service.CreateApiDeploymentRequest, dict]] = None, + *, + parent: Optional[str] = None, + api_deployment: Optional[registry_models.ApiDeployment] = None, + api_deployment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Creates a specified deployment. + + .. 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 apigee_registry_v1 + + def sample_create_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiDeploymentRequest( + parent="parent_value", + api_deployment_id="api_deployment_id_value", + ) + + # Make the request + response = client.create_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest, dict]): + The request object. Request message for + CreateApiDeployment. + parent (str): + Required. The parent, which owns this collection of + deployments. Format: ``projects/*/locations/*/apis/*`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): + Required. The deployment to create. + This corresponds to the ``api_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + api_deployment_id (str): + Required. The ID to use for the deployment, which will + become the final component of the deployment's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``api_deployment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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, api_deployment, api_deployment_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.CreateApiDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.CreateApiDeploymentRequest): + request = registry_service.CreateApiDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if api_deployment is not None: + request.api_deployment = api_deployment + if api_deployment_id is not None: + request.api_deployment_id = api_deployment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_api_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_api_deployment(self, + request: Optional[Union[registry_service.UpdateApiDeploymentRequest, dict]] = None, + *, + api_deployment: Optional[registry_models.ApiDeployment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Used to modify a specified deployment. + + .. 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 apigee_registry_v1 + + def sample_update_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiDeploymentRequest( + ) + + # Make the request + response = client.update_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest, dict]): + The request object. Request message for + UpdateApiDeployment. + api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): + Required. The deployment to update. + + The ``name`` field is used to identify the deployment to + update. Format: + ``projects/*/locations/*/apis/*/deployments/*`` + + This corresponds to the ``api_deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields + are updated that are set in the request message (fields + set to default values are ignored). If an asterisk "*" + is specified, all fields are updated, including fields + that are unspecified/default in the request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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([api_deployment, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.UpdateApiDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.UpdateApiDeploymentRequest): + request = registry_service.UpdateApiDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if api_deployment is not None: + request.api_deployment = api_deployment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_api_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("api_deployment.name", request.api_deployment.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_api_deployment(self, + request: Optional[Union[registry_service.DeleteApiDeploymentRequest, 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]] = (), + ) -> None: + r"""Removes a specified deployment, all revisions, and + all child resources (e.g., artifacts). + + .. 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 apigee_registry_v1 + + def sample_delete_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRequest( + name="name_value", + ) + + # Make the request + client.delete_api_deployment(request=request) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest, dict]): + The request object. Request message for + DeleteApiDeployment. + name (str): + Required. The name of the deployment to delete. Format: + ``projects/*/locations/*/apis/*/deployments/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 registry_service.DeleteApiDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.DeleteApiDeploymentRequest): + request = registry_service.DeleteApiDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_api_deployment] + + # 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 tag_api_deployment_revision(self, + request: Optional[Union[registry_service.TagApiDeploymentRevisionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Adds a tag to a specified revision of a + deployment. + + .. 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 apigee_registry_v1 + + def sample_tag_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiDeploymentRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = client.tag_api_deployment_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest, dict]): + The request object. Request message for + TagApiDeploymentRevision. + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.TagApiDeploymentRevisionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.TagApiDeploymentRevisionRequest): + request = registry_service.TagApiDeploymentRevisionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.tag_api_deployment_revision] + + # 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_api_deployment_revisions(self, + request: Optional[Union[registry_service.ListApiDeploymentRevisionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListApiDeploymentRevisionsPager: + r"""Lists all revisions of a deployment. + Revisions are returned in descending order of revision + creation time. + + .. 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 apigee_registry_v1 + + def sample_list_api_deployment_revisions(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_deployment_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest, dict]): + The request object. Request message for + ListApiDeploymentRevisions. + 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsPager: + Response message for + ListApiDeploymentRevisionsResponse. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.ListApiDeploymentRevisionsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ListApiDeploymentRevisionsRequest): + request = registry_service.ListApiDeploymentRevisionsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_api_deployment_revisions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListApiDeploymentRevisionsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def rollback_api_deployment(self, + request: Optional[Union[registry_service.RollbackApiDeploymentRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.ApiDeployment: + r"""Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + .. 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 apigee_registry_v1 + + def sample_rollback_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiDeploymentRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = client.rollback_api_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest, dict]): + The request object. Request message for + RollbackApiDeployment. + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.RollbackApiDeploymentRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.RollbackApiDeploymentRequest): + request = registry_service.RollbackApiDeploymentRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rollback_api_deployment] + + # 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_api_deployment_revision(self, + request: Optional[Union[registry_service.DeleteApiDeploymentRevisionRequest, 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]] = (), + ) -> registry_models.ApiDeployment: + r"""Deletes a revision of a deployment. + + .. 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 apigee_registry_v1 + + def sample_delete_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_api_deployment_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest, dict]): + The request object. Request message for + DeleteApiDeploymentRevision. + name (str): + Required. The name of the deployment revision to be + deleted, with a revision ID explicitly included. + + Example: + ``projects/sample/locations/global/apis/petstore/deployments/prod@c7cfa2a8`` + + 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.apigee_registry_v1.types.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + # 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 registry_service.DeleteApiDeploymentRevisionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.DeleteApiDeploymentRevisionRequest): + request = registry_service.DeleteApiDeploymentRevisionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_api_deployment_revision] + + # 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_artifacts(self, + request: Optional[Union[registry_service.ListArtifactsRequest, 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.ListArtifactsPager: + r"""Returns matching artifacts. + + .. 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 apigee_registry_v1 + + def sample_list_artifacts(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListArtifactsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_artifacts(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ListArtifactsRequest, dict]): + The request object. Request message for ListArtifacts. + parent (str): + Required. The parent, which owns this collection of + artifacts. Format: ``{parent}`` + + 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.apigee_registry_v1.services.registry.pagers.ListArtifactsPager: + Response message for ListArtifacts. + 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 registry_service.ListArtifactsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ListArtifactsRequest): + request = registry_service.ListArtifactsRequest(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_artifacts] + + # 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.ListArtifactsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_artifact(self, + request: Optional[Union[registry_service.GetArtifactRequest, 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]] = (), + ) -> registry_models.Artifact: + r"""Returns a specified artifact. + + .. 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 apigee_registry_v1 + + def sample_get_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactRequest( + name="name_value", + ) + + # Make the request + response = client.get_artifact(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetArtifactRequest, dict]): + The request object. Request message for GetArtifact. + name (str): + Required. The name of the artifact to retrieve. Format: + ``{parent}/artifacts/*`` + + 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.apigee_registry_v1.types.Artifact: + Artifacts of resources. Artifacts are unique (single-value) per resource + and are used to store metadata that is too large or + numerous to be stored directly on the resource. Since + artifacts are stored separately from parent + resources, they should generally be used for metadata + that is needed infrequently, i.e., not for display in + primary views of the resource but perhaps displayed + or downloaded upon request. The ListArtifacts method + allows artifacts to be quickly enumerated and checked + for presence without downloading their + (potentially-large) contents. + + """ + # 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 registry_service.GetArtifactRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.GetArtifactRequest): + request = registry_service.GetArtifactRequest(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_artifact] + + # 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_artifact_contents(self, + request: Optional[Union[registry_service.GetArtifactContentsRequest, 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]] = (), + ) -> httpbody_pb2.HttpBody: + r"""Returns the contents of a specified artifact. If artifacts are + stored with GZip compression, the default behavior is to return + the artifact uncompressed (the mime_type response field + indicates the exact format returned). + + .. 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 apigee_registry_v1 + + def sample_get_artifact_contents(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactContentsRequest( + name="name_value", + ) + + # Make the request + response = client.get_artifact_contents(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest, dict]): + The request object. Request message for + GetArtifactContents. + name (str): + Required. The name of the artifact whose contents should + be retrieved. Format: ``{parent}/artifacts/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It should only be used for + payload formats that can't be represented as JSON, + such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as + the response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request + fields and also want access to the raw HTTP body. + + Example: + + message GetResourceRequest { + // A unique request id. string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + # 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 registry_service.GetArtifactContentsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.GetArtifactContentsRequest): + request = registry_service.GetArtifactContentsRequest(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_artifact_contents] + + # 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 create_artifact(self, + request: Optional[Union[registry_service.CreateArtifactRequest, dict]] = None, + *, + parent: Optional[str] = None, + artifact: Optional[registry_models.Artifact] = None, + artifact_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Artifact: + r"""Creates a specified artifact. + + .. 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 apigee_registry_v1 + + def sample_create_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateArtifactRequest( + parent="parent_value", + artifact_id="artifact_id_value", + ) + + # Make the request + response = client.create_artifact(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.CreateArtifactRequest, dict]): + The request object. Request message for CreateArtifact. + parent (str): + Required. The parent, which owns this collection of + artifacts. Format: ``{parent}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + artifact (google.cloud.apigee_registry_v1.types.Artifact): + Required. The artifact to create. + This corresponds to the ``artifact`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + artifact_id (str): + Required. The ID to use for the artifact, which will + become the final component of the artifact's resource + name. + + This value should be 4-63 characters, and valid + characters are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + + This corresponds to the ``artifact_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.apigee_registry_v1.types.Artifact: + Artifacts of resources. Artifacts are unique (single-value) per resource + and are used to store metadata that is too large or + numerous to be stored directly on the resource. Since + artifacts are stored separately from parent + resources, they should generally be used for metadata + that is needed infrequently, i.e., not for display in + primary views of the resource but perhaps displayed + or downloaded upon request. The ListArtifacts method + allows artifacts to be quickly enumerated and checked + for presence without downloading their + (potentially-large) contents. + + """ + # 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, artifact, artifact_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # Minor optimization to avoid making a copy if the user passes + # in a registry_service.CreateArtifactRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.CreateArtifactRequest): + request = registry_service.CreateArtifactRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if artifact is not None: + request.artifact = artifact + if artifact_id is not None: + request.artifact_id = artifact_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_artifact] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def replace_artifact(self, + request: Optional[Union[registry_service.ReplaceArtifactRequest, dict]] = None, + *, + artifact: Optional[registry_models.Artifact] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> registry_models.Artifact: + r"""Used to replace a specified artifact. + + .. 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 apigee_registry_v1 + + def sample_replace_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ReplaceArtifactRequest( + ) + + # Make the request + response = client.replace_artifact(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest, dict]): + The request object. Request message for ReplaceArtifact. + artifact (google.cloud.apigee_registry_v1.types.Artifact): + Required. The artifact to replace. + + The ``name`` field is used to identify the artifact to + replace. Format: ``{parent}/artifacts/*`` + + This corresponds to the ``artifact`` 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.apigee_registry_v1.types.Artifact: + Artifacts of resources. Artifacts are unique (single-value) per resource + and are used to store metadata that is too large or + numerous to be stored directly on the resource. Since + artifacts are stored separately from parent + resources, they should generally be used for metadata + that is needed infrequently, i.e., not for display in + primary views of the resource but perhaps displayed + or downloaded upon request. The ListArtifacts method + allows artifacts to be quickly enumerated and checked + for presence without downloading their + (potentially-large) contents. + + """ + # 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([artifact]) + 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 registry_service.ReplaceArtifactRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.ReplaceArtifactRequest): + request = registry_service.ReplaceArtifactRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if artifact is not None: + request.artifact = artifact + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.replace_artifact] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("artifact.name", request.artifact.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_artifact(self, + request: Optional[Union[registry_service.DeleteArtifactRequest, 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]] = (), + ) -> None: + r"""Removes a specified artifact. + + .. 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 apigee_registry_v1 + + def sample_delete_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteArtifactRequest( + name="name_value", + ) + + # Make the request + client.delete_artifact(request=request) + + Args: + request (Union[google.cloud.apigee_registry_v1.types.DeleteArtifactRequest, dict]): + The request object. Request message for DeleteArtifact. + name (str): + Required. The name of the artifact to delete. Format: + ``{parent}/artifacts/*`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # 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 registry_service.DeleteArtifactRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registry_service.DeleteArtifactRequest): + request = registry_service.DeleteArtifactRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_artifact] + + # 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 __enter__(self) -> "RegistryClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + 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 set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + 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__) + + +__all__ = ( + "RegistryClient", +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py new file mode 100644 index 0000000..fb70da3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py @@ -0,0 +1,866 @@ +# -*- 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. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service + + +class ListApisPager: + """A pager for iterating through ``list_apis`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` object, and + provides an ``__iter__`` method to iterate through its + ``apis`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApis`` requests and continue to iterate + through the ``apis`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` + 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[..., registry_service.ListApisResponse], + request: registry_service.ListApisRequest, + response: registry_service.ListApisResponse, + *, + 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.apigee_registry_v1.types.ListApisRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApisResponse): + 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 = registry_service.ListApisRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registry_service.ListApisResponse]: + 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[registry_models.Api]: + for page in self.pages: + yield from page.apis + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApisAsyncPager: + """A pager for iterating through ``list_apis`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``apis`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApis`` requests and continue to iterate + through the ``apis`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` + 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[registry_service.ListApisResponse]], + request: registry_service.ListApisRequest, + response: registry_service.ListApisResponse, + *, + 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.apigee_registry_v1.types.ListApisRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApisResponse): + 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 = registry_service.ListApisRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registry_service.ListApisResponse]: + 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[registry_models.Api]: + async def async_generator(): + async for page in self.pages: + for response in page.apis: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiVersionsPager: + """A pager for iterating through ``list_api_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``api_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApiVersions`` requests and continue to iterate + through the ``api_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` + 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[..., registry_service.ListApiVersionsResponse], + request: registry_service.ListApiVersionsRequest, + response: registry_service.ListApiVersionsResponse, + *, + 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.apigee_registry_v1.types.ListApiVersionsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiVersionsResponse): + 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 = registry_service.ListApiVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registry_service.ListApiVersionsResponse]: + 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[registry_models.ApiVersion]: + for page in self.pages: + yield from page.api_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiVersionsAsyncPager: + """A pager for iterating through ``list_api_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``api_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApiVersions`` requests and continue to iterate + through the ``api_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` + 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[registry_service.ListApiVersionsResponse]], + request: registry_service.ListApiVersionsRequest, + response: registry_service.ListApiVersionsResponse, + *, + 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.apigee_registry_v1.types.ListApiVersionsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiVersionsResponse): + 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 = registry_service.ListApiVersionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registry_service.ListApiVersionsResponse]: + 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[registry_models.ApiVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.api_versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiSpecsPager: + """A pager for iterating through ``list_api_specs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``api_specs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApiSpecs`` requests and continue to iterate + through the ``api_specs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` + 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[..., registry_service.ListApiSpecsResponse], + request: registry_service.ListApiSpecsRequest, + response: registry_service.ListApiSpecsResponse, + *, + 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.apigee_registry_v1.types.ListApiSpecsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiSpecsResponse): + 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 = registry_service.ListApiSpecsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registry_service.ListApiSpecsResponse]: + 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[registry_models.ApiSpec]: + for page in self.pages: + yield from page.api_specs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiSpecsAsyncPager: + """A pager for iterating through ``list_api_specs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``api_specs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApiSpecs`` requests and continue to iterate + through the ``api_specs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` + 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[registry_service.ListApiSpecsResponse]], + request: registry_service.ListApiSpecsRequest, + response: registry_service.ListApiSpecsResponse, + *, + 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.apigee_registry_v1.types.ListApiSpecsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiSpecsResponse): + 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 = registry_service.ListApiSpecsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registry_service.ListApiSpecsResponse]: + 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[registry_models.ApiSpec]: + async def async_generator(): + async for page in self.pages: + for response in page.api_specs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiSpecRevisionsPager: + """A pager for iterating through ``list_api_spec_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``api_specs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApiSpecRevisions`` requests and continue to iterate + through the ``api_specs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` + 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[..., registry_service.ListApiSpecRevisionsResponse], + request: registry_service.ListApiSpecRevisionsRequest, + response: registry_service.ListApiSpecRevisionsResponse, + *, + 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.apigee_registry_v1.types.ListApiSpecRevisionsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse): + 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 = registry_service.ListApiSpecRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registry_service.ListApiSpecRevisionsResponse]: + 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[registry_models.ApiSpec]: + for page in self.pages: + yield from page.api_specs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiSpecRevisionsAsyncPager: + """A pager for iterating through ``list_api_spec_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``api_specs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApiSpecRevisions`` requests and continue to iterate + through the ``api_specs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` + 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[registry_service.ListApiSpecRevisionsResponse]], + request: registry_service.ListApiSpecRevisionsRequest, + response: registry_service.ListApiSpecRevisionsResponse, + *, + 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.apigee_registry_v1.types.ListApiSpecRevisionsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse): + 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 = registry_service.ListApiSpecRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registry_service.ListApiSpecRevisionsResponse]: + 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[registry_models.ApiSpec]: + async def async_generator(): + async for page in self.pages: + for response in page.api_specs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiDeploymentsPager: + """A pager for iterating through ``list_api_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``api_deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApiDeployments`` requests and continue to iterate + through the ``api_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` + 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[..., registry_service.ListApiDeploymentsResponse], + request: registry_service.ListApiDeploymentsRequest, + response: registry_service.ListApiDeploymentsResponse, + *, + 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.apigee_registry_v1.types.ListApiDeploymentsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse): + 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 = registry_service.ListApiDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registry_service.ListApiDeploymentsResponse]: + 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[registry_models.ApiDeployment]: + for page in self.pages: + yield from page.api_deployments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiDeploymentsAsyncPager: + """A pager for iterating through ``list_api_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``api_deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApiDeployments`` requests and continue to iterate + through the ``api_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` + 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[registry_service.ListApiDeploymentsResponse]], + request: registry_service.ListApiDeploymentsRequest, + response: registry_service.ListApiDeploymentsResponse, + *, + 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.apigee_registry_v1.types.ListApiDeploymentsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse): + 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 = registry_service.ListApiDeploymentsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registry_service.ListApiDeploymentsResponse]: + 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[registry_models.ApiDeployment]: + async def async_generator(): + async for page in self.pages: + for response in page.api_deployments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiDeploymentRevisionsPager: + """A pager for iterating through ``list_api_deployment_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``api_deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApiDeploymentRevisions`` requests and continue to iterate + through the ``api_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` + 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[..., registry_service.ListApiDeploymentRevisionsResponse], + request: registry_service.ListApiDeploymentRevisionsRequest, + response: registry_service.ListApiDeploymentRevisionsResponse, + *, + 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.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse): + 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 = registry_service.ListApiDeploymentRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registry_service.ListApiDeploymentRevisionsResponse]: + 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[registry_models.ApiDeployment]: + for page in self.pages: + yield from page.api_deployments + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListApiDeploymentRevisionsAsyncPager: + """A pager for iterating through ``list_api_deployment_revisions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``api_deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApiDeploymentRevisions`` requests and continue to iterate + through the ``api_deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` + 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[registry_service.ListApiDeploymentRevisionsResponse]], + request: registry_service.ListApiDeploymentRevisionsRequest, + response: registry_service.ListApiDeploymentRevisionsResponse, + *, + 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.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse): + 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 = registry_service.ListApiDeploymentRevisionsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registry_service.ListApiDeploymentRevisionsResponse]: + 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[registry_models.ApiDeployment]: + async def async_generator(): + async for page in self.pages: + for response in page.api_deployments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListArtifactsPager: + """A pager for iterating through ``list_artifacts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``artifacts`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListArtifacts`` requests and continue to iterate + through the ``artifacts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` + 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[..., registry_service.ListArtifactsResponse], + request: registry_service.ListArtifactsRequest, + response: registry_service.ListArtifactsResponse, + *, + 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.apigee_registry_v1.types.ListArtifactsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListArtifactsResponse): + 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 = registry_service.ListArtifactsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[registry_service.ListArtifactsResponse]: + 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[registry_models.Artifact]: + for page in self.pages: + yield from page.artifacts + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListArtifactsAsyncPager: + """A pager for iterating through ``list_artifacts`` requests. + + This class thinly wraps an initial + :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``artifacts`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListArtifacts`` requests and continue to iterate + through the ``artifacts`` field on the + corresponding responses. + + All the usual :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` + 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[registry_service.ListArtifactsResponse]], + request: registry_service.ListArtifactsRequest, + response: registry_service.ListArtifactsResponse, + *, + 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.apigee_registry_v1.types.ListArtifactsRequest): + The initial request object. + response (google.cloud.apigee_registry_v1.types.ListArtifactsResponse): + 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 = registry_service.ListArtifactsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[registry_service.ListArtifactsResponse]: + 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[registry_models.Artifact]: + async def async_generator(): + async for page in self.pages: + for response in page.artifacts: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py new file mode 100644 index 0000000..8e7b424 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RegistryTransport +from .grpc import RegistryGrpcTransport +from .grpc_asyncio import RegistryGrpcAsyncIOTransport +from .rest import RegistryRestTransport +from .rest import RegistryRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RegistryTransport]] +_transport_registry['grpc'] = RegistryGrpcTransport +_transport_registry['grpc_asyncio'] = RegistryGrpcAsyncIOTransport +_transport_registry['rest'] = RegistryRestTransport + +__all__ = ( + 'RegistryTransport', + 'RegistryGrpcTransport', + 'RegistryGrpcAsyncIOTransport', + 'RegistryRestTransport', + 'RegistryRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py new file mode 100644 index 0000000..90a2f72 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py @@ -0,0 +1,1010 @@ +# -*- 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.apigee_registry_v1 import gapic_version as package_version + +import google.auth # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service +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 empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class RegistryTransport(abc.ABC): + """Abstract transport class for Registry.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'apigeeregistry.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_apis: gapic_v1.method.wrap_method( + self.list_apis, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_api: gapic_v1.method.wrap_method( + self.get_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_api: gapic_v1.method.wrap_method( + self.create_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_api: gapic_v1.method.wrap_method( + self.update_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_api: gapic_v1.method.wrap_method( + self.delete_api, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_api_versions: gapic_v1.method.wrap_method( + self.list_api_versions, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_api_version: gapic_v1.method.wrap_method( + self.get_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_api_version: gapic_v1.method.wrap_method( + self.create_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_api_version: gapic_v1.method.wrap_method( + self.update_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_api_version: gapic_v1.method.wrap_method( + self.delete_api_version, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_api_specs: gapic_v1.method.wrap_method( + self.list_api_specs, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_api_spec: gapic_v1.method.wrap_method( + self.get_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_api_spec_contents: gapic_v1.method.wrap_method( + self.get_api_spec_contents, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_api_spec: gapic_v1.method.wrap_method( + self.create_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_api_spec: gapic_v1.method.wrap_method( + self.update_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_api_spec: gapic_v1.method.wrap_method( + self.delete_api_spec, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.tag_api_spec_revision: gapic_v1.method.wrap_method( + self.tag_api_spec_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_api_spec_revisions: gapic_v1.method.wrap_method( + self.list_api_spec_revisions, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.rollback_api_spec: gapic_v1.method.wrap_method( + self.rollback_api_spec, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_api_spec_revision: gapic_v1.method.wrap_method( + self.delete_api_spec_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_api_deployments: gapic_v1.method.wrap_method( + self.list_api_deployments, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_api_deployment: gapic_v1.method.wrap_method( + self.get_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_api_deployment: gapic_v1.method.wrap_method( + self.create_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_api_deployment: gapic_v1.method.wrap_method( + self.update_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_api_deployment: gapic_v1.method.wrap_method( + self.delete_api_deployment, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.tag_api_deployment_revision: gapic_v1.method.wrap_method( + self.tag_api_deployment_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_api_deployment_revisions: gapic_v1.method.wrap_method( + self.list_api_deployment_revisions, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.rollback_api_deployment: gapic_v1.method.wrap_method( + self.rollback_api_deployment, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_api_deployment_revision: gapic_v1.method.wrap_method( + self.delete_api_deployment_revision, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_artifacts: gapic_v1.method.wrap_method( + self.list_artifacts, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_artifact: gapic_v1.method.wrap_method( + self.get_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_artifact_contents: gapic_v1.method.wrap_method( + self.get_artifact_contents, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_artifact: gapic_v1.method.wrap_method( + self.create_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.replace_artifact: gapic_v1.method.wrap_method( + self.replace_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_artifact: gapic_v1.method.wrap_method( + self.delete_artifact, + default_retry=retries.Retry( +initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def list_apis(self) -> Callable[ + [registry_service.ListApisRequest], + Union[ + registry_service.ListApisResponse, + Awaitable[registry_service.ListApisResponse] + ]]: + raise NotImplementedError() + + @property + def get_api(self) -> Callable[ + [registry_service.GetApiRequest], + Union[ + registry_models.Api, + Awaitable[registry_models.Api] + ]]: + raise NotImplementedError() + + @property + def create_api(self) -> Callable[ + [registry_service.CreateApiRequest], + Union[ + registry_models.Api, + Awaitable[registry_models.Api] + ]]: + raise NotImplementedError() + + @property + def update_api(self) -> Callable[ + [registry_service.UpdateApiRequest], + Union[ + registry_models.Api, + Awaitable[registry_models.Api] + ]]: + raise NotImplementedError() + + @property + def delete_api(self) -> Callable[ + [registry_service.DeleteApiRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_api_versions(self) -> Callable[ + [registry_service.ListApiVersionsRequest], + Union[ + registry_service.ListApiVersionsResponse, + Awaitable[registry_service.ListApiVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_api_version(self) -> Callable[ + [registry_service.GetApiVersionRequest], + Union[ + registry_models.ApiVersion, + Awaitable[registry_models.ApiVersion] + ]]: + raise NotImplementedError() + + @property + def create_api_version(self) -> Callable[ + [registry_service.CreateApiVersionRequest], + Union[ + registry_models.ApiVersion, + Awaitable[registry_models.ApiVersion] + ]]: + raise NotImplementedError() + + @property + def update_api_version(self) -> Callable[ + [registry_service.UpdateApiVersionRequest], + Union[ + registry_models.ApiVersion, + Awaitable[registry_models.ApiVersion] + ]]: + raise NotImplementedError() + + @property + def delete_api_version(self) -> Callable[ + [registry_service.DeleteApiVersionRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def list_api_specs(self) -> Callable[ + [registry_service.ListApiSpecsRequest], + Union[ + registry_service.ListApiSpecsResponse, + Awaitable[registry_service.ListApiSpecsResponse] + ]]: + raise NotImplementedError() + + @property + def get_api_spec(self) -> Callable[ + [registry_service.GetApiSpecRequest], + Union[ + registry_models.ApiSpec, + Awaitable[registry_models.ApiSpec] + ]]: + raise NotImplementedError() + + @property + def get_api_spec_contents(self) -> Callable[ + [registry_service.GetApiSpecContentsRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def create_api_spec(self) -> Callable[ + [registry_service.CreateApiSpecRequest], + Union[ + registry_models.ApiSpec, + Awaitable[registry_models.ApiSpec] + ]]: + raise NotImplementedError() + + @property + def update_api_spec(self) -> Callable[ + [registry_service.UpdateApiSpecRequest], + Union[ + registry_models.ApiSpec, + Awaitable[registry_models.ApiSpec] + ]]: + raise NotImplementedError() + + @property + def delete_api_spec(self) -> Callable[ + [registry_service.DeleteApiSpecRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def tag_api_spec_revision(self) -> Callable[ + [registry_service.TagApiSpecRevisionRequest], + Union[ + registry_models.ApiSpec, + Awaitable[registry_models.ApiSpec] + ]]: + raise NotImplementedError() + + @property + def list_api_spec_revisions(self) -> Callable[ + [registry_service.ListApiSpecRevisionsRequest], + Union[ + registry_service.ListApiSpecRevisionsResponse, + Awaitable[registry_service.ListApiSpecRevisionsResponse] + ]]: + raise NotImplementedError() + + @property + def rollback_api_spec(self) -> Callable[ + [registry_service.RollbackApiSpecRequest], + Union[ + registry_models.ApiSpec, + Awaitable[registry_models.ApiSpec] + ]]: + raise NotImplementedError() + + @property + def delete_api_spec_revision(self) -> Callable[ + [registry_service.DeleteApiSpecRevisionRequest], + Union[ + registry_models.ApiSpec, + Awaitable[registry_models.ApiSpec] + ]]: + raise NotImplementedError() + + @property + def list_api_deployments(self) -> Callable[ + [registry_service.ListApiDeploymentsRequest], + Union[ + registry_service.ListApiDeploymentsResponse, + Awaitable[registry_service.ListApiDeploymentsResponse] + ]]: + raise NotImplementedError() + + @property + def get_api_deployment(self) -> Callable[ + [registry_service.GetApiDeploymentRequest], + Union[ + registry_models.ApiDeployment, + Awaitable[registry_models.ApiDeployment] + ]]: + raise NotImplementedError() + + @property + def create_api_deployment(self) -> Callable[ + [registry_service.CreateApiDeploymentRequest], + Union[ + registry_models.ApiDeployment, + Awaitable[registry_models.ApiDeployment] + ]]: + raise NotImplementedError() + + @property + def update_api_deployment(self) -> Callable[ + [registry_service.UpdateApiDeploymentRequest], + Union[ + registry_models.ApiDeployment, + Awaitable[registry_models.ApiDeployment] + ]]: + raise NotImplementedError() + + @property + def delete_api_deployment(self) -> Callable[ + [registry_service.DeleteApiDeploymentRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def tag_api_deployment_revision(self) -> Callable[ + [registry_service.TagApiDeploymentRevisionRequest], + Union[ + registry_models.ApiDeployment, + Awaitable[registry_models.ApiDeployment] + ]]: + raise NotImplementedError() + + @property + def list_api_deployment_revisions(self) -> Callable[ + [registry_service.ListApiDeploymentRevisionsRequest], + Union[ + registry_service.ListApiDeploymentRevisionsResponse, + Awaitable[registry_service.ListApiDeploymentRevisionsResponse] + ]]: + raise NotImplementedError() + + @property + def rollback_api_deployment(self) -> Callable[ + [registry_service.RollbackApiDeploymentRequest], + Union[ + registry_models.ApiDeployment, + Awaitable[registry_models.ApiDeployment] + ]]: + raise NotImplementedError() + + @property + def delete_api_deployment_revision(self) -> Callable[ + [registry_service.DeleteApiDeploymentRevisionRequest], + Union[ + registry_models.ApiDeployment, + Awaitable[registry_models.ApiDeployment] + ]]: + raise NotImplementedError() + + @property + def list_artifacts(self) -> Callable[ + [registry_service.ListArtifactsRequest], + Union[ + registry_service.ListArtifactsResponse, + Awaitable[registry_service.ListArtifactsResponse] + ]]: + raise NotImplementedError() + + @property + def get_artifact(self) -> Callable[ + [registry_service.GetArtifactRequest], + Union[ + registry_models.Artifact, + Awaitable[registry_models.Artifact] + ]]: + raise NotImplementedError() + + @property + def get_artifact_contents(self) -> Callable[ + [registry_service.GetArtifactContentsRequest], + Union[ + httpbody_pb2.HttpBody, + Awaitable[httpbody_pb2.HttpBody] + ]]: + raise NotImplementedError() + + @property + def create_artifact(self) -> Callable[ + [registry_service.CreateArtifactRequest], + Union[ + registry_models.Artifact, + Awaitable[registry_models.Artifact] + ]]: + raise NotImplementedError() + + @property + def replace_artifact(self) -> Callable[ + [registry_service.ReplaceArtifactRequest], + Union[ + registry_models.Artifact, + Awaitable[registry_models.Artifact] + ]]: + raise NotImplementedError() + + @property + def delete_artifact(self) -> Callable[ + [registry_service.DeleteArtifactRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + 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 set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + 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() + + +__all__ = ( + 'RegistryTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py new file mode 100644 index 0000000..c98f6da --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py @@ -0,0 +1,1362 @@ +# -*- 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. +# +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service +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 empty_pb2 # type: ignore +from .base import RegistryTransport, DEFAULT_CLIENT_INFO + + +class RegistryGrpcTransport(RegistryTransport): + """gRPC backend transport for Registry. + + The Registry service allows teams to manage descriptions of + APIs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + _stubs: Dict[str, Callable] + + def __init__(self, *, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[grpc.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def list_apis(self) -> Callable[ + [registry_service.ListApisRequest], + registry_service.ListApisResponse]: + r"""Return a callable for the list apis method over gRPC. + + Returns matching APIs. + + Returns: + Callable[[~.ListApisRequest], + ~.ListApisResponse]: + 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_apis' not in self._stubs: + self._stubs['list_apis'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApis', + request_serializer=registry_service.ListApisRequest.serialize, + response_deserializer=registry_service.ListApisResponse.deserialize, + ) + return self._stubs['list_apis'] + + @property + def get_api(self) -> Callable[ + [registry_service.GetApiRequest], + registry_models.Api]: + r"""Return a callable for the get api method over gRPC. + + Returns a specified API. + + Returns: + Callable[[~.GetApiRequest], + ~.Api]: + 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_api' not in self._stubs: + self._stubs['get_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApi', + request_serializer=registry_service.GetApiRequest.serialize, + response_deserializer=registry_models.Api.deserialize, + ) + return self._stubs['get_api'] + + @property + def create_api(self) -> Callable[ + [registry_service.CreateApiRequest], + registry_models.Api]: + r"""Return a callable for the create api method over gRPC. + + Creates a specified API. + + Returns: + Callable[[~.CreateApiRequest], + ~.Api]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api' not in self._stubs: + self._stubs['create_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApi', + request_serializer=registry_service.CreateApiRequest.serialize, + response_deserializer=registry_models.Api.deserialize, + ) + return self._stubs['create_api'] + + @property + def update_api(self) -> Callable[ + [registry_service.UpdateApiRequest], + registry_models.Api]: + r"""Return a callable for the update api method over gRPC. + + Used to modify a specified API. + + Returns: + Callable[[~.UpdateApiRequest], + ~.Api]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api' not in self._stubs: + self._stubs['update_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApi', + request_serializer=registry_service.UpdateApiRequest.serialize, + response_deserializer=registry_models.Api.deserialize, + ) + return self._stubs['update_api'] + + @property + def delete_api(self) -> Callable[ + [registry_service.DeleteApiRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete api method over gRPC. + + Removes a specified API and all of the resources that + it owns. + + Returns: + Callable[[~.DeleteApiRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api' not in self._stubs: + self._stubs['delete_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApi', + request_serializer=registry_service.DeleteApiRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api'] + + @property + def list_api_versions(self) -> Callable[ + [registry_service.ListApiVersionsRequest], + registry_service.ListApiVersionsResponse]: + r"""Return a callable for the list api versions method over gRPC. + + Returns matching versions. + + Returns: + Callable[[~.ListApiVersionsRequest], + ~.ListApiVersionsResponse]: + 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_api_versions' not in self._stubs: + self._stubs['list_api_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiVersions', + request_serializer=registry_service.ListApiVersionsRequest.serialize, + response_deserializer=registry_service.ListApiVersionsResponse.deserialize, + ) + return self._stubs['list_api_versions'] + + @property + def get_api_version(self) -> Callable[ + [registry_service.GetApiVersionRequest], + registry_models.ApiVersion]: + r"""Return a callable for the get api version method over gRPC. + + Returns a specified version. + + Returns: + Callable[[~.GetApiVersionRequest], + ~.ApiVersion]: + 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_api_version' not in self._stubs: + self._stubs['get_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiVersion', + request_serializer=registry_service.GetApiVersionRequest.serialize, + response_deserializer=registry_models.ApiVersion.deserialize, + ) + return self._stubs['get_api_version'] + + @property + def create_api_version(self) -> Callable[ + [registry_service.CreateApiVersionRequest], + registry_models.ApiVersion]: + r"""Return a callable for the create api version method over gRPC. + + Creates a specified version. + + Returns: + Callable[[~.CreateApiVersionRequest], + ~.ApiVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api_version' not in self._stubs: + self._stubs['create_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApiVersion', + request_serializer=registry_service.CreateApiVersionRequest.serialize, + response_deserializer=registry_models.ApiVersion.deserialize, + ) + return self._stubs['create_api_version'] + + @property + def update_api_version(self) -> Callable[ + [registry_service.UpdateApiVersionRequest], + registry_models.ApiVersion]: + r"""Return a callable for the update api version method over gRPC. + + Used to modify a specified version. + + Returns: + Callable[[~.UpdateApiVersionRequest], + ~.ApiVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api_version' not in self._stubs: + self._stubs['update_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApiVersion', + request_serializer=registry_service.UpdateApiVersionRequest.serialize, + response_deserializer=registry_models.ApiVersion.deserialize, + ) + return self._stubs['update_api_version'] + + @property + def delete_api_version(self) -> Callable[ + [registry_service.DeleteApiVersionRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete api version method over gRPC. + + Removes a specified version and all of the resources + that it owns. + + Returns: + Callable[[~.DeleteApiVersionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_version' not in self._stubs: + self._stubs['delete_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiVersion', + request_serializer=registry_service.DeleteApiVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api_version'] + + @property + def list_api_specs(self) -> Callable[ + [registry_service.ListApiSpecsRequest], + registry_service.ListApiSpecsResponse]: + r"""Return a callable for the list api specs method over gRPC. + + Returns matching specs. + + Returns: + Callable[[~.ListApiSpecsRequest], + ~.ListApiSpecsResponse]: + 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_api_specs' not in self._stubs: + self._stubs['list_api_specs'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecs', + request_serializer=registry_service.ListApiSpecsRequest.serialize, + response_deserializer=registry_service.ListApiSpecsResponse.deserialize, + ) + return self._stubs['list_api_specs'] + + @property + def get_api_spec(self) -> Callable[ + [registry_service.GetApiSpecRequest], + registry_models.ApiSpec]: + r"""Return a callable for the get api spec method over gRPC. + + Returns a specified spec. + + Returns: + Callable[[~.GetApiSpecRequest], + ~.ApiSpec]: + 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_api_spec' not in self._stubs: + self._stubs['get_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiSpec', + request_serializer=registry_service.GetApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['get_api_spec'] + + @property + def get_api_spec_contents(self) -> Callable[ + [registry_service.GetApiSpecContentsRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the get api spec contents method over gRPC. + + Returns the contents of a specified spec. If specs are stored + with GZip compression, the default behavior is to return the + spec uncompressed (the mime_type response field indicates the + exact format returned). + + Returns: + Callable[[~.GetApiSpecContentsRequest], + ~.HttpBody]: + 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_api_spec_contents' not in self._stubs: + self._stubs['get_api_spec_contents'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiSpecContents', + request_serializer=registry_service.GetApiSpecContentsRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['get_api_spec_contents'] + + @property + def create_api_spec(self) -> Callable[ + [registry_service.CreateApiSpecRequest], + registry_models.ApiSpec]: + r"""Return a callable for the create api spec method over gRPC. + + Creates a specified spec. + + Returns: + Callable[[~.CreateApiSpecRequest], + ~.ApiSpec]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api_spec' not in self._stubs: + self._stubs['create_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApiSpec', + request_serializer=registry_service.CreateApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['create_api_spec'] + + @property + def update_api_spec(self) -> Callable[ + [registry_service.UpdateApiSpecRequest], + registry_models.ApiSpec]: + r"""Return a callable for the update api spec method over gRPC. + + Used to modify a specified spec. + + Returns: + Callable[[~.UpdateApiSpecRequest], + ~.ApiSpec]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api_spec' not in self._stubs: + self._stubs['update_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApiSpec', + request_serializer=registry_service.UpdateApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['update_api_spec'] + + @property + def delete_api_spec(self) -> Callable[ + [registry_service.DeleteApiSpecRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete api spec method over gRPC. + + Removes a specified spec, all revisions, and all + child resources (e.g., artifacts). + + Returns: + Callable[[~.DeleteApiSpecRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_spec' not in self._stubs: + self._stubs['delete_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpec', + request_serializer=registry_service.DeleteApiSpecRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api_spec'] + + @property + def tag_api_spec_revision(self) -> Callable[ + [registry_service.TagApiSpecRevisionRequest], + registry_models.ApiSpec]: + r"""Return a callable for the tag api spec revision method over gRPC. + + Adds a tag to a specified revision of a spec. + + Returns: + Callable[[~.TagApiSpecRevisionRequest], + ~.ApiSpec]: + 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 'tag_api_spec_revision' not in self._stubs: + self._stubs['tag_api_spec_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/TagApiSpecRevision', + request_serializer=registry_service.TagApiSpecRevisionRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['tag_api_spec_revision'] + + @property + def list_api_spec_revisions(self) -> Callable[ + [registry_service.ListApiSpecRevisionsRequest], + registry_service.ListApiSpecRevisionsResponse]: + r"""Return a callable for the list api spec revisions method over gRPC. + + Lists all revisions of a spec. + Revisions are returned in descending order of revision + creation time. + + Returns: + Callable[[~.ListApiSpecRevisionsRequest], + ~.ListApiSpecRevisionsResponse]: + 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_api_spec_revisions' not in self._stubs: + self._stubs['list_api_spec_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecRevisions', + request_serializer=registry_service.ListApiSpecRevisionsRequest.serialize, + response_deserializer=registry_service.ListApiSpecRevisionsResponse.deserialize, + ) + return self._stubs['list_api_spec_revisions'] + + @property + def rollback_api_spec(self) -> Callable[ + [registry_service.RollbackApiSpecRequest], + registry_models.ApiSpec]: + r"""Return a callable for the rollback api spec method over gRPC. + + Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + Returns: + Callable[[~.RollbackApiSpecRequest], + ~.ApiSpec]: + 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 'rollback_api_spec' not in self._stubs: + self._stubs['rollback_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/RollbackApiSpec', + request_serializer=registry_service.RollbackApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['rollback_api_spec'] + + @property + def delete_api_spec_revision(self) -> Callable[ + [registry_service.DeleteApiSpecRevisionRequest], + registry_models.ApiSpec]: + r"""Return a callable for the delete api spec revision method over gRPC. + + Deletes a revision of a spec. + + Returns: + Callable[[~.DeleteApiSpecRevisionRequest], + ~.ApiSpec]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_spec_revision' not in self._stubs: + self._stubs['delete_api_spec_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpecRevision', + request_serializer=registry_service.DeleteApiSpecRevisionRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['delete_api_spec_revision'] + + @property + def list_api_deployments(self) -> Callable[ + [registry_service.ListApiDeploymentsRequest], + registry_service.ListApiDeploymentsResponse]: + r"""Return a callable for the list api deployments method over gRPC. + + Returns matching deployments. + + Returns: + Callable[[~.ListApiDeploymentsRequest], + ~.ListApiDeploymentsResponse]: + 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_api_deployments' not in self._stubs: + self._stubs['list_api_deployments'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiDeployments', + request_serializer=registry_service.ListApiDeploymentsRequest.serialize, + response_deserializer=registry_service.ListApiDeploymentsResponse.deserialize, + ) + return self._stubs['list_api_deployments'] + + @property + def get_api_deployment(self) -> Callable[ + [registry_service.GetApiDeploymentRequest], + registry_models.ApiDeployment]: + r"""Return a callable for the get api deployment method over gRPC. + + Returns a specified deployment. + + Returns: + Callable[[~.GetApiDeploymentRequest], + ~.ApiDeployment]: + 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_api_deployment' not in self._stubs: + self._stubs['get_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiDeployment', + request_serializer=registry_service.GetApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['get_api_deployment'] + + @property + def create_api_deployment(self) -> Callable[ + [registry_service.CreateApiDeploymentRequest], + registry_models.ApiDeployment]: + r"""Return a callable for the create api deployment method over gRPC. + + Creates a specified deployment. + + Returns: + Callable[[~.CreateApiDeploymentRequest], + ~.ApiDeployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api_deployment' not in self._stubs: + self._stubs['create_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApiDeployment', + request_serializer=registry_service.CreateApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['create_api_deployment'] + + @property + def update_api_deployment(self) -> Callable[ + [registry_service.UpdateApiDeploymentRequest], + registry_models.ApiDeployment]: + r"""Return a callable for the update api deployment method over gRPC. + + Used to modify a specified deployment. + + Returns: + Callable[[~.UpdateApiDeploymentRequest], + ~.ApiDeployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api_deployment' not in self._stubs: + self._stubs['update_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApiDeployment', + request_serializer=registry_service.UpdateApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['update_api_deployment'] + + @property + def delete_api_deployment(self) -> Callable[ + [registry_service.DeleteApiDeploymentRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete api deployment method over gRPC. + + Removes a specified deployment, all revisions, and + all child resources (e.g., artifacts). + + Returns: + Callable[[~.DeleteApiDeploymentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_deployment' not in self._stubs: + self._stubs['delete_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeployment', + request_serializer=registry_service.DeleteApiDeploymentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api_deployment'] + + @property + def tag_api_deployment_revision(self) -> Callable[ + [registry_service.TagApiDeploymentRevisionRequest], + registry_models.ApiDeployment]: + r"""Return a callable for the tag api deployment revision method over gRPC. + + Adds a tag to a specified revision of a + deployment. + + Returns: + Callable[[~.TagApiDeploymentRevisionRequest], + ~.ApiDeployment]: + 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 'tag_api_deployment_revision' not in self._stubs: + self._stubs['tag_api_deployment_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/TagApiDeploymentRevision', + request_serializer=registry_service.TagApiDeploymentRevisionRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['tag_api_deployment_revision'] + + @property + def list_api_deployment_revisions(self) -> Callable[ + [registry_service.ListApiDeploymentRevisionsRequest], + registry_service.ListApiDeploymentRevisionsResponse]: + r"""Return a callable for the list api deployment revisions method over gRPC. + + Lists all revisions of a deployment. + Revisions are returned in descending order of revision + creation time. + + Returns: + Callable[[~.ListApiDeploymentRevisionsRequest], + ~.ListApiDeploymentRevisionsResponse]: + 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_api_deployment_revisions' not in self._stubs: + self._stubs['list_api_deployment_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiDeploymentRevisions', + request_serializer=registry_service.ListApiDeploymentRevisionsRequest.serialize, + response_deserializer=registry_service.ListApiDeploymentRevisionsResponse.deserialize, + ) + return self._stubs['list_api_deployment_revisions'] + + @property + def rollback_api_deployment(self) -> Callable[ + [registry_service.RollbackApiDeploymentRequest], + registry_models.ApiDeployment]: + r"""Return a callable for the rollback api deployment method over gRPC. + + Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + Returns: + Callable[[~.RollbackApiDeploymentRequest], + ~.ApiDeployment]: + 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 'rollback_api_deployment' not in self._stubs: + self._stubs['rollback_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/RollbackApiDeployment', + request_serializer=registry_service.RollbackApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['rollback_api_deployment'] + + @property + def delete_api_deployment_revision(self) -> Callable[ + [registry_service.DeleteApiDeploymentRevisionRequest], + registry_models.ApiDeployment]: + r"""Return a callable for the delete api deployment revision method over gRPC. + + Deletes a revision of a deployment. + + Returns: + Callable[[~.DeleteApiDeploymentRevisionRequest], + ~.ApiDeployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_deployment_revision' not in self._stubs: + self._stubs['delete_api_deployment_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeploymentRevision', + request_serializer=registry_service.DeleteApiDeploymentRevisionRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['delete_api_deployment_revision'] + + @property + def list_artifacts(self) -> Callable[ + [registry_service.ListArtifactsRequest], + registry_service.ListArtifactsResponse]: + r"""Return a callable for the list artifacts method over gRPC. + + Returns matching artifacts. + + Returns: + Callable[[~.ListArtifactsRequest], + ~.ListArtifactsResponse]: + 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_artifacts' not in self._stubs: + self._stubs['list_artifacts'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListArtifacts', + request_serializer=registry_service.ListArtifactsRequest.serialize, + response_deserializer=registry_service.ListArtifactsResponse.deserialize, + ) + return self._stubs['list_artifacts'] + + @property + def get_artifact(self) -> Callable[ + [registry_service.GetArtifactRequest], + registry_models.Artifact]: + r"""Return a callable for the get artifact method over gRPC. + + Returns a specified artifact. + + Returns: + Callable[[~.GetArtifactRequest], + ~.Artifact]: + 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_artifact' not in self._stubs: + self._stubs['get_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetArtifact', + request_serializer=registry_service.GetArtifactRequest.serialize, + response_deserializer=registry_models.Artifact.deserialize, + ) + return self._stubs['get_artifact'] + + @property + def get_artifact_contents(self) -> Callable[ + [registry_service.GetArtifactContentsRequest], + httpbody_pb2.HttpBody]: + r"""Return a callable for the get artifact contents method over gRPC. + + Returns the contents of a specified artifact. If artifacts are + stored with GZip compression, the default behavior is to return + the artifact uncompressed (the mime_type response field + indicates the exact format returned). + + Returns: + Callable[[~.GetArtifactContentsRequest], + ~.HttpBody]: + 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_artifact_contents' not in self._stubs: + self._stubs['get_artifact_contents'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetArtifactContents', + request_serializer=registry_service.GetArtifactContentsRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['get_artifact_contents'] + + @property + def create_artifact(self) -> Callable[ + [registry_service.CreateArtifactRequest], + registry_models.Artifact]: + r"""Return a callable for the create artifact method over gRPC. + + Creates a specified artifact. + + Returns: + Callable[[~.CreateArtifactRequest], + ~.Artifact]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_artifact' not in self._stubs: + self._stubs['create_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateArtifact', + request_serializer=registry_service.CreateArtifactRequest.serialize, + response_deserializer=registry_models.Artifact.deserialize, + ) + return self._stubs['create_artifact'] + + @property + def replace_artifact(self) -> Callable[ + [registry_service.ReplaceArtifactRequest], + registry_models.Artifact]: + r"""Return a callable for the replace artifact method over gRPC. + + Used to replace a specified artifact. + + Returns: + Callable[[~.ReplaceArtifactRequest], + ~.Artifact]: + 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 'replace_artifact' not in self._stubs: + self._stubs['replace_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ReplaceArtifact', + request_serializer=registry_service.ReplaceArtifactRequest.serialize, + response_deserializer=registry_models.Artifact.deserialize, + ) + return self._stubs['replace_artifact'] + + @property + def delete_artifact(self) -> Callable[ + [registry_service.DeleteArtifactRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete artifact method over gRPC. + + Removes a specified artifact. + + Returns: + Callable[[~.DeleteArtifactRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_artifact' not in self._stubs: + self._stubs['delete_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteArtifact', + request_serializer=registry_service.DeleteArtifactRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_artifact'] + + 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 set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'RegistryGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py new file mode 100644 index 0000000..669459a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py @@ -0,0 +1,1361 @@ +# -*- 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. +# +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service +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 empty_pb2 # type: ignore +from .base import RegistryTransport, DEFAULT_CLIENT_INFO +from .grpc import RegistryGrpcTransport + + +class RegistryGrpcAsyncIOTransport(RegistryTransport): + """gRPC AsyncIO backend transport for Registry. + + The Registry service allows teams to manage descriptions of + APIs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel(cls, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[aio.Channel] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if ``channel`` is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if channel: + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def list_apis(self) -> Callable[ + [registry_service.ListApisRequest], + Awaitable[registry_service.ListApisResponse]]: + r"""Return a callable for the list apis method over gRPC. + + Returns matching APIs. + + Returns: + Callable[[~.ListApisRequest], + Awaitable[~.ListApisResponse]]: + 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_apis' not in self._stubs: + self._stubs['list_apis'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApis', + request_serializer=registry_service.ListApisRequest.serialize, + response_deserializer=registry_service.ListApisResponse.deserialize, + ) + return self._stubs['list_apis'] + + @property + def get_api(self) -> Callable[ + [registry_service.GetApiRequest], + Awaitable[registry_models.Api]]: + r"""Return a callable for the get api method over gRPC. + + Returns a specified API. + + Returns: + Callable[[~.GetApiRequest], + Awaitable[~.Api]]: + 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_api' not in self._stubs: + self._stubs['get_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApi', + request_serializer=registry_service.GetApiRequest.serialize, + response_deserializer=registry_models.Api.deserialize, + ) + return self._stubs['get_api'] + + @property + def create_api(self) -> Callable[ + [registry_service.CreateApiRequest], + Awaitable[registry_models.Api]]: + r"""Return a callable for the create api method over gRPC. + + Creates a specified API. + + Returns: + Callable[[~.CreateApiRequest], + Awaitable[~.Api]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api' not in self._stubs: + self._stubs['create_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApi', + request_serializer=registry_service.CreateApiRequest.serialize, + response_deserializer=registry_models.Api.deserialize, + ) + return self._stubs['create_api'] + + @property + def update_api(self) -> Callable[ + [registry_service.UpdateApiRequest], + Awaitable[registry_models.Api]]: + r"""Return a callable for the update api method over gRPC. + + Used to modify a specified API. + + Returns: + Callable[[~.UpdateApiRequest], + Awaitable[~.Api]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api' not in self._stubs: + self._stubs['update_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApi', + request_serializer=registry_service.UpdateApiRequest.serialize, + response_deserializer=registry_models.Api.deserialize, + ) + return self._stubs['update_api'] + + @property + def delete_api(self) -> Callable[ + [registry_service.DeleteApiRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete api method over gRPC. + + Removes a specified API and all of the resources that + it owns. + + Returns: + Callable[[~.DeleteApiRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api' not in self._stubs: + self._stubs['delete_api'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApi', + request_serializer=registry_service.DeleteApiRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api'] + + @property + def list_api_versions(self) -> Callable[ + [registry_service.ListApiVersionsRequest], + Awaitable[registry_service.ListApiVersionsResponse]]: + r"""Return a callable for the list api versions method over gRPC. + + Returns matching versions. + + Returns: + Callable[[~.ListApiVersionsRequest], + Awaitable[~.ListApiVersionsResponse]]: + 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_api_versions' not in self._stubs: + self._stubs['list_api_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiVersions', + request_serializer=registry_service.ListApiVersionsRequest.serialize, + response_deserializer=registry_service.ListApiVersionsResponse.deserialize, + ) + return self._stubs['list_api_versions'] + + @property + def get_api_version(self) -> Callable[ + [registry_service.GetApiVersionRequest], + Awaitable[registry_models.ApiVersion]]: + r"""Return a callable for the get api version method over gRPC. + + Returns a specified version. + + Returns: + Callable[[~.GetApiVersionRequest], + Awaitable[~.ApiVersion]]: + 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_api_version' not in self._stubs: + self._stubs['get_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiVersion', + request_serializer=registry_service.GetApiVersionRequest.serialize, + response_deserializer=registry_models.ApiVersion.deserialize, + ) + return self._stubs['get_api_version'] + + @property + def create_api_version(self) -> Callable[ + [registry_service.CreateApiVersionRequest], + Awaitable[registry_models.ApiVersion]]: + r"""Return a callable for the create api version method over gRPC. + + Creates a specified version. + + Returns: + Callable[[~.CreateApiVersionRequest], + Awaitable[~.ApiVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api_version' not in self._stubs: + self._stubs['create_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApiVersion', + request_serializer=registry_service.CreateApiVersionRequest.serialize, + response_deserializer=registry_models.ApiVersion.deserialize, + ) + return self._stubs['create_api_version'] + + @property + def update_api_version(self) -> Callable[ + [registry_service.UpdateApiVersionRequest], + Awaitable[registry_models.ApiVersion]]: + r"""Return a callable for the update api version method over gRPC. + + Used to modify a specified version. + + Returns: + Callable[[~.UpdateApiVersionRequest], + Awaitable[~.ApiVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api_version' not in self._stubs: + self._stubs['update_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApiVersion', + request_serializer=registry_service.UpdateApiVersionRequest.serialize, + response_deserializer=registry_models.ApiVersion.deserialize, + ) + return self._stubs['update_api_version'] + + @property + def delete_api_version(self) -> Callable[ + [registry_service.DeleteApiVersionRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete api version method over gRPC. + + Removes a specified version and all of the resources + that it owns. + + Returns: + Callable[[~.DeleteApiVersionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_version' not in self._stubs: + self._stubs['delete_api_version'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiVersion', + request_serializer=registry_service.DeleteApiVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api_version'] + + @property + def list_api_specs(self) -> Callable[ + [registry_service.ListApiSpecsRequest], + Awaitable[registry_service.ListApiSpecsResponse]]: + r"""Return a callable for the list api specs method over gRPC. + + Returns matching specs. + + Returns: + Callable[[~.ListApiSpecsRequest], + Awaitable[~.ListApiSpecsResponse]]: + 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_api_specs' not in self._stubs: + self._stubs['list_api_specs'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecs', + request_serializer=registry_service.ListApiSpecsRequest.serialize, + response_deserializer=registry_service.ListApiSpecsResponse.deserialize, + ) + return self._stubs['list_api_specs'] + + @property + def get_api_spec(self) -> Callable[ + [registry_service.GetApiSpecRequest], + Awaitable[registry_models.ApiSpec]]: + r"""Return a callable for the get api spec method over gRPC. + + Returns a specified spec. + + Returns: + Callable[[~.GetApiSpecRequest], + Awaitable[~.ApiSpec]]: + 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_api_spec' not in self._stubs: + self._stubs['get_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiSpec', + request_serializer=registry_service.GetApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['get_api_spec'] + + @property + def get_api_spec_contents(self) -> Callable[ + [registry_service.GetApiSpecContentsRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the get api spec contents method over gRPC. + + Returns the contents of a specified spec. If specs are stored + with GZip compression, the default behavior is to return the + spec uncompressed (the mime_type response field indicates the + exact format returned). + + Returns: + Callable[[~.GetApiSpecContentsRequest], + Awaitable[~.HttpBody]]: + 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_api_spec_contents' not in self._stubs: + self._stubs['get_api_spec_contents'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiSpecContents', + request_serializer=registry_service.GetApiSpecContentsRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['get_api_spec_contents'] + + @property + def create_api_spec(self) -> Callable[ + [registry_service.CreateApiSpecRequest], + Awaitable[registry_models.ApiSpec]]: + r"""Return a callable for the create api spec method over gRPC. + + Creates a specified spec. + + Returns: + Callable[[~.CreateApiSpecRequest], + Awaitable[~.ApiSpec]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api_spec' not in self._stubs: + self._stubs['create_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApiSpec', + request_serializer=registry_service.CreateApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['create_api_spec'] + + @property + def update_api_spec(self) -> Callable[ + [registry_service.UpdateApiSpecRequest], + Awaitable[registry_models.ApiSpec]]: + r"""Return a callable for the update api spec method over gRPC. + + Used to modify a specified spec. + + Returns: + Callable[[~.UpdateApiSpecRequest], + Awaitable[~.ApiSpec]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api_spec' not in self._stubs: + self._stubs['update_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApiSpec', + request_serializer=registry_service.UpdateApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['update_api_spec'] + + @property + def delete_api_spec(self) -> Callable[ + [registry_service.DeleteApiSpecRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete api spec method over gRPC. + + Removes a specified spec, all revisions, and all + child resources (e.g., artifacts). + + Returns: + Callable[[~.DeleteApiSpecRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_spec' not in self._stubs: + self._stubs['delete_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpec', + request_serializer=registry_service.DeleteApiSpecRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api_spec'] + + @property + def tag_api_spec_revision(self) -> Callable[ + [registry_service.TagApiSpecRevisionRequest], + Awaitable[registry_models.ApiSpec]]: + r"""Return a callable for the tag api spec revision method over gRPC. + + Adds a tag to a specified revision of a spec. + + Returns: + Callable[[~.TagApiSpecRevisionRequest], + Awaitable[~.ApiSpec]]: + 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 'tag_api_spec_revision' not in self._stubs: + self._stubs['tag_api_spec_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/TagApiSpecRevision', + request_serializer=registry_service.TagApiSpecRevisionRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['tag_api_spec_revision'] + + @property + def list_api_spec_revisions(self) -> Callable[ + [registry_service.ListApiSpecRevisionsRequest], + Awaitable[registry_service.ListApiSpecRevisionsResponse]]: + r"""Return a callable for the list api spec revisions method over gRPC. + + Lists all revisions of a spec. + Revisions are returned in descending order of revision + creation time. + + Returns: + Callable[[~.ListApiSpecRevisionsRequest], + Awaitable[~.ListApiSpecRevisionsResponse]]: + 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_api_spec_revisions' not in self._stubs: + self._stubs['list_api_spec_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecRevisions', + request_serializer=registry_service.ListApiSpecRevisionsRequest.serialize, + response_deserializer=registry_service.ListApiSpecRevisionsResponse.deserialize, + ) + return self._stubs['list_api_spec_revisions'] + + @property + def rollback_api_spec(self) -> Callable[ + [registry_service.RollbackApiSpecRequest], + Awaitable[registry_models.ApiSpec]]: + r"""Return a callable for the rollback api spec method over gRPC. + + Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + Returns: + Callable[[~.RollbackApiSpecRequest], + Awaitable[~.ApiSpec]]: + 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 'rollback_api_spec' not in self._stubs: + self._stubs['rollback_api_spec'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/RollbackApiSpec', + request_serializer=registry_service.RollbackApiSpecRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['rollback_api_spec'] + + @property + def delete_api_spec_revision(self) -> Callable[ + [registry_service.DeleteApiSpecRevisionRequest], + Awaitable[registry_models.ApiSpec]]: + r"""Return a callable for the delete api spec revision method over gRPC. + + Deletes a revision of a spec. + + Returns: + Callable[[~.DeleteApiSpecRevisionRequest], + Awaitable[~.ApiSpec]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_spec_revision' not in self._stubs: + self._stubs['delete_api_spec_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpecRevision', + request_serializer=registry_service.DeleteApiSpecRevisionRequest.serialize, + response_deserializer=registry_models.ApiSpec.deserialize, + ) + return self._stubs['delete_api_spec_revision'] + + @property + def list_api_deployments(self) -> Callable[ + [registry_service.ListApiDeploymentsRequest], + Awaitable[registry_service.ListApiDeploymentsResponse]]: + r"""Return a callable for the list api deployments method over gRPC. + + Returns matching deployments. + + Returns: + Callable[[~.ListApiDeploymentsRequest], + Awaitable[~.ListApiDeploymentsResponse]]: + 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_api_deployments' not in self._stubs: + self._stubs['list_api_deployments'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiDeployments', + request_serializer=registry_service.ListApiDeploymentsRequest.serialize, + response_deserializer=registry_service.ListApiDeploymentsResponse.deserialize, + ) + return self._stubs['list_api_deployments'] + + @property + def get_api_deployment(self) -> Callable[ + [registry_service.GetApiDeploymentRequest], + Awaitable[registry_models.ApiDeployment]]: + r"""Return a callable for the get api deployment method over gRPC. + + Returns a specified deployment. + + Returns: + Callable[[~.GetApiDeploymentRequest], + Awaitable[~.ApiDeployment]]: + 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_api_deployment' not in self._stubs: + self._stubs['get_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetApiDeployment', + request_serializer=registry_service.GetApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['get_api_deployment'] + + @property + def create_api_deployment(self) -> Callable[ + [registry_service.CreateApiDeploymentRequest], + Awaitable[registry_models.ApiDeployment]]: + r"""Return a callable for the create api deployment method over gRPC. + + Creates a specified deployment. + + Returns: + Callable[[~.CreateApiDeploymentRequest], + Awaitable[~.ApiDeployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_api_deployment' not in self._stubs: + self._stubs['create_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateApiDeployment', + request_serializer=registry_service.CreateApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['create_api_deployment'] + + @property + def update_api_deployment(self) -> Callable[ + [registry_service.UpdateApiDeploymentRequest], + Awaitable[registry_models.ApiDeployment]]: + r"""Return a callable for the update api deployment method over gRPC. + + Used to modify a specified deployment. + + Returns: + Callable[[~.UpdateApiDeploymentRequest], + Awaitable[~.ApiDeployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'update_api_deployment' not in self._stubs: + self._stubs['update_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/UpdateApiDeployment', + request_serializer=registry_service.UpdateApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['update_api_deployment'] + + @property + def delete_api_deployment(self) -> Callable[ + [registry_service.DeleteApiDeploymentRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete api deployment method over gRPC. + + Removes a specified deployment, all revisions, and + all child resources (e.g., artifacts). + + Returns: + Callable[[~.DeleteApiDeploymentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_deployment' not in self._stubs: + self._stubs['delete_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeployment', + request_serializer=registry_service.DeleteApiDeploymentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_api_deployment'] + + @property + def tag_api_deployment_revision(self) -> Callable[ + [registry_service.TagApiDeploymentRevisionRequest], + Awaitable[registry_models.ApiDeployment]]: + r"""Return a callable for the tag api deployment revision method over gRPC. + + Adds a tag to a specified revision of a + deployment. + + Returns: + Callable[[~.TagApiDeploymentRevisionRequest], + Awaitable[~.ApiDeployment]]: + 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 'tag_api_deployment_revision' not in self._stubs: + self._stubs['tag_api_deployment_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/TagApiDeploymentRevision', + request_serializer=registry_service.TagApiDeploymentRevisionRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['tag_api_deployment_revision'] + + @property + def list_api_deployment_revisions(self) -> Callable[ + [registry_service.ListApiDeploymentRevisionsRequest], + Awaitable[registry_service.ListApiDeploymentRevisionsResponse]]: + r"""Return a callable for the list api deployment revisions method over gRPC. + + Lists all revisions of a deployment. + Revisions are returned in descending order of revision + creation time. + + Returns: + Callable[[~.ListApiDeploymentRevisionsRequest], + Awaitable[~.ListApiDeploymentRevisionsResponse]]: + 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_api_deployment_revisions' not in self._stubs: + self._stubs['list_api_deployment_revisions'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListApiDeploymentRevisions', + request_serializer=registry_service.ListApiDeploymentRevisionsRequest.serialize, + response_deserializer=registry_service.ListApiDeploymentRevisionsResponse.deserialize, + ) + return self._stubs['list_api_deployment_revisions'] + + @property + def rollback_api_deployment(self) -> Callable[ + [registry_service.RollbackApiDeploymentRequest], + Awaitable[registry_models.ApiDeployment]]: + r"""Return a callable for the rollback api deployment method over gRPC. + + Sets the current revision to a specified prior + revision. Note that this creates a new revision with a + new revision ID. + + Returns: + Callable[[~.RollbackApiDeploymentRequest], + Awaitable[~.ApiDeployment]]: + 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 'rollback_api_deployment' not in self._stubs: + self._stubs['rollback_api_deployment'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/RollbackApiDeployment', + request_serializer=registry_service.RollbackApiDeploymentRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['rollback_api_deployment'] + + @property + def delete_api_deployment_revision(self) -> Callable[ + [registry_service.DeleteApiDeploymentRevisionRequest], + Awaitable[registry_models.ApiDeployment]]: + r"""Return a callable for the delete api deployment revision method over gRPC. + + Deletes a revision of a deployment. + + Returns: + Callable[[~.DeleteApiDeploymentRevisionRequest], + Awaitable[~.ApiDeployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_api_deployment_revision' not in self._stubs: + self._stubs['delete_api_deployment_revision'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeploymentRevision', + request_serializer=registry_service.DeleteApiDeploymentRevisionRequest.serialize, + response_deserializer=registry_models.ApiDeployment.deserialize, + ) + return self._stubs['delete_api_deployment_revision'] + + @property + def list_artifacts(self) -> Callable[ + [registry_service.ListArtifactsRequest], + Awaitable[registry_service.ListArtifactsResponse]]: + r"""Return a callable for the list artifacts method over gRPC. + + Returns matching artifacts. + + Returns: + Callable[[~.ListArtifactsRequest], + Awaitable[~.ListArtifactsResponse]]: + 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_artifacts' not in self._stubs: + self._stubs['list_artifacts'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ListArtifacts', + request_serializer=registry_service.ListArtifactsRequest.serialize, + response_deserializer=registry_service.ListArtifactsResponse.deserialize, + ) + return self._stubs['list_artifacts'] + + @property + def get_artifact(self) -> Callable[ + [registry_service.GetArtifactRequest], + Awaitable[registry_models.Artifact]]: + r"""Return a callable for the get artifact method over gRPC. + + Returns a specified artifact. + + Returns: + Callable[[~.GetArtifactRequest], + Awaitable[~.Artifact]]: + 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_artifact' not in self._stubs: + self._stubs['get_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetArtifact', + request_serializer=registry_service.GetArtifactRequest.serialize, + response_deserializer=registry_models.Artifact.deserialize, + ) + return self._stubs['get_artifact'] + + @property + def get_artifact_contents(self) -> Callable[ + [registry_service.GetArtifactContentsRequest], + Awaitable[httpbody_pb2.HttpBody]]: + r"""Return a callable for the get artifact contents method over gRPC. + + Returns the contents of a specified artifact. If artifacts are + stored with GZip compression, the default behavior is to return + the artifact uncompressed (the mime_type response field + indicates the exact format returned). + + Returns: + Callable[[~.GetArtifactContentsRequest], + Awaitable[~.HttpBody]]: + 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_artifact_contents' not in self._stubs: + self._stubs['get_artifact_contents'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/GetArtifactContents', + request_serializer=registry_service.GetArtifactContentsRequest.serialize, + response_deserializer=httpbody_pb2.HttpBody.FromString, + ) + return self._stubs['get_artifact_contents'] + + @property + def create_artifact(self) -> Callable[ + [registry_service.CreateArtifactRequest], + Awaitable[registry_models.Artifact]]: + r"""Return a callable for the create artifact method over gRPC. + + Creates a specified artifact. + + Returns: + Callable[[~.CreateArtifactRequest], + Awaitable[~.Artifact]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'create_artifact' not in self._stubs: + self._stubs['create_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/CreateArtifact', + request_serializer=registry_service.CreateArtifactRequest.serialize, + response_deserializer=registry_models.Artifact.deserialize, + ) + return self._stubs['create_artifact'] + + @property + def replace_artifact(self) -> Callable[ + [registry_service.ReplaceArtifactRequest], + Awaitable[registry_models.Artifact]]: + r"""Return a callable for the replace artifact method over gRPC. + + Used to replace a specified artifact. + + Returns: + Callable[[~.ReplaceArtifactRequest], + Awaitable[~.Artifact]]: + 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 'replace_artifact' not in self._stubs: + self._stubs['replace_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/ReplaceArtifact', + request_serializer=registry_service.ReplaceArtifactRequest.serialize, + response_deserializer=registry_models.Artifact.deserialize, + ) + return self._stubs['replace_artifact'] + + @property + def delete_artifact(self) -> Callable[ + [registry_service.DeleteArtifactRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete artifact method over gRPC. + + Removes a specified artifact. + + Returns: + Callable[[~.DeleteArtifactRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'delete_artifact' not in self._stubs: + self._stubs['delete_artifact'] = self.grpc_channel.unary_unary( + '/google.cloud.apigeeregistry.v1.Registry/DeleteArtifact', + request_serializer=registry_service.DeleteArtifactRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_artifact'] + + 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"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ( + 'RegistryGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py new file mode 100644 index 0000000..f57a8fa --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py @@ -0,0 +1,5357 @@ +# -*- 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. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +import grpc # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 +from requests import __version__ as requests_version +import dataclasses +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.api import httpbody_pb2 # type: ignore +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service +from google.protobuf import empty_pb2 # type: ignore + +from .base import RegistryTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RegistryRestInterceptor: + """Interceptor for Registry. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the RegistryRestTransport. + + .. code-block:: python + class MyCustomRegistryInterceptor(RegistryRestInterceptor): + def pre_create_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_api(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_api_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_api_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_api_spec(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_api_spec(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_api_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_api_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_artifact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_artifact(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_api_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_api_deployment_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_api_deployment_revision(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_api_spec(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_api_spec_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_api_spec_revision(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_api_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_artifact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_api(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_api_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_api_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_api_spec(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_api_spec(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_api_spec_contents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_api_spec_contents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_api_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_api_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_artifact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_artifact(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_artifact_contents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_artifact_contents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_api_deployment_revisions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_api_deployment_revisions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_api_deployments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_api_deployments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_apis(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_apis(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_api_spec_revisions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_api_spec_revisions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_api_specs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_api_specs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_api_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_api_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_artifacts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_artifacts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_replace_artifact(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_replace_artifact(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rollback_api_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rollback_api_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rollback_api_spec(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rollback_api_spec(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_tag_api_deployment_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_tag_api_deployment_revision(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_tag_api_spec_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_tag_api_spec_revision(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_api(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_api(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_api_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_api_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_api_spec(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_api_spec(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_api_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_api_version(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RegistryRestTransport(interceptor=MyCustomRegistryInterceptor()) + client = RegistryClient(transport=transport) + + + """ + def pre_create_api(self, request: registry_service.CreateApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_create_api(self, response: registry_models.Api) -> registry_models.Api: + """Post-rpc interceptor for create_api + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_create_api_deployment(self, request: registry_service.CreateApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiDeploymentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_api_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_create_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: + """Post-rpc interceptor for create_api_deployment + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_create_api_spec(self, request: registry_service.CreateApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiSpecRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_api_spec + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_create_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: + """Post-rpc interceptor for create_api_spec + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_create_api_version(self, request: registry_service.CreateApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_api_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_create_api_version(self, response: registry_models.ApiVersion) -> registry_models.ApiVersion: + """Post-rpc interceptor for create_api_version + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_create_artifact(self, request: registry_service.CreateArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateArtifactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_artifact + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_create_artifact(self, response: registry_models.Artifact) -> registry_models.Artifact: + """Post-rpc interceptor for create_artifact + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_delete_api(self, request: registry_service.DeleteApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def pre_delete_api_deployment(self, request: registry_service.DeleteApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiDeploymentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def pre_delete_api_deployment_revision(self, request: registry_service.DeleteApiDeploymentRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiDeploymentRevisionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api_deployment_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_delete_api_deployment_revision(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: + """Post-rpc interceptor for delete_api_deployment_revision + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_delete_api_spec(self, request: registry_service.DeleteApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiSpecRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api_spec + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def pre_delete_api_spec_revision(self, request: registry_service.DeleteApiSpecRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiSpecRevisionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api_spec_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_delete_api_spec_revision(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: + """Post-rpc interceptor for delete_api_spec_revision + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_delete_api_version(self, request: registry_service.DeleteApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_api_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def pre_delete_artifact(self, request: registry_service.DeleteArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteArtifactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_artifact + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def pre_get_api(self, request: registry_service.GetApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_api(self, response: registry_models.Api) -> registry_models.Api: + """Post-rpc interceptor for get_api + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_api_deployment(self, request: registry_service.GetApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiDeploymentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_api_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: + """Post-rpc interceptor for get_api_deployment + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_api_spec(self, request: registry_service.GetApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiSpecRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_api_spec + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: + """Post-rpc interceptor for get_api_spec + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_api_spec_contents(self, request: registry_service.GetApiSpecContentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiSpecContentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_api_spec_contents + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_api_spec_contents(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for get_api_spec_contents + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_api_version(self, request: registry_service.GetApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_api_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_api_version(self, response: registry_models.ApiVersion) -> registry_models.ApiVersion: + """Post-rpc interceptor for get_api_version + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_artifact(self, request: registry_service.GetArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetArtifactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_artifact + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_artifact(self, response: registry_models.Artifact) -> registry_models.Artifact: + """Post-rpc interceptor for get_artifact + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_artifact_contents(self, request: registry_service.GetArtifactContentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetArtifactContentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_artifact_contents + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_artifact_contents(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: + """Post-rpc interceptor for get_artifact_contents + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_api_deployment_revisions(self, request: registry_service.ListApiDeploymentRevisionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiDeploymentRevisionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_api_deployment_revisions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_api_deployment_revisions(self, response: registry_service.ListApiDeploymentRevisionsResponse) -> registry_service.ListApiDeploymentRevisionsResponse: + """Post-rpc interceptor for list_api_deployment_revisions + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_api_deployments(self, request: registry_service.ListApiDeploymentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiDeploymentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_api_deployments + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_api_deployments(self, response: registry_service.ListApiDeploymentsResponse) -> registry_service.ListApiDeploymentsResponse: + """Post-rpc interceptor for list_api_deployments + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_apis(self, request: registry_service.ListApisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApisRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_apis + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_apis(self, response: registry_service.ListApisResponse) -> registry_service.ListApisResponse: + """Post-rpc interceptor for list_apis + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_api_spec_revisions(self, request: registry_service.ListApiSpecRevisionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiSpecRevisionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_api_spec_revisions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_api_spec_revisions(self, response: registry_service.ListApiSpecRevisionsResponse) -> registry_service.ListApiSpecRevisionsResponse: + """Post-rpc interceptor for list_api_spec_revisions + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_api_specs(self, request: registry_service.ListApiSpecsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiSpecsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_api_specs + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_api_specs(self, response: registry_service.ListApiSpecsResponse) -> registry_service.ListApiSpecsResponse: + """Post-rpc interceptor for list_api_specs + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_api_versions(self, request: registry_service.ListApiVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiVersionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_api_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_api_versions(self, response: registry_service.ListApiVersionsResponse) -> registry_service.ListApiVersionsResponse: + """Post-rpc interceptor for list_api_versions + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_artifacts(self, request: registry_service.ListArtifactsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListArtifactsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_artifacts + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_artifacts(self, response: registry_service.ListArtifactsResponse) -> registry_service.ListArtifactsResponse: + """Post-rpc interceptor for list_artifacts + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_replace_artifact(self, request: registry_service.ReplaceArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ReplaceArtifactRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for replace_artifact + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_replace_artifact(self, response: registry_models.Artifact) -> registry_models.Artifact: + """Post-rpc interceptor for replace_artifact + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_rollback_api_deployment(self, request: registry_service.RollbackApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.RollbackApiDeploymentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for rollback_api_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_rollback_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: + """Post-rpc interceptor for rollback_api_deployment + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_rollback_api_spec(self, request: registry_service.RollbackApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.RollbackApiSpecRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for rollback_api_spec + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_rollback_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: + """Post-rpc interceptor for rollback_api_spec + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_tag_api_deployment_revision(self, request: registry_service.TagApiDeploymentRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.TagApiDeploymentRevisionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for tag_api_deployment_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_tag_api_deployment_revision(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: + """Post-rpc interceptor for tag_api_deployment_revision + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_tag_api_spec_revision(self, request: registry_service.TagApiSpecRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.TagApiSpecRevisionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for tag_api_spec_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_tag_api_spec_revision(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: + """Post-rpc interceptor for tag_api_spec_revision + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_update_api(self, request: registry_service.UpdateApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_api + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_update_api(self, response: registry_models.Api) -> registry_models.Api: + """Post-rpc interceptor for update_api + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_update_api_deployment(self, request: registry_service.UpdateApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiDeploymentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_api_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_update_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: + """Post-rpc interceptor for update_api_deployment + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_update_api_spec(self, request: registry_service.UpdateApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiSpecRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_api_spec + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_update_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: + """Post-rpc interceptor for update_api_spec + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_update_api_version(self, request: registry_service.UpdateApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_api_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_update_api_version(self, response: registry_models.ApiVersion) -> registry_models.ApiVersion: + """Post-rpc interceptor for update_api_version + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_cancel_operation( + self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_cancel_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_delete_operation( + self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_delete_operation( + self, response: None + ) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_get_operation( + self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + def pre_list_operations( + self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Registry server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Registry server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RegistryRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegistryRestInterceptor + + +class RegistryRestTransport(RegistryTransport): + """REST backend transport for Registry. + + The Registry service allows teams to manage descriptions of + APIs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__(self, *, + host: str = 'apigeeregistry.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[ + ], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + interceptor: Optional[RegistryRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or RegistryRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateApi(RegistryRestStub): + def __hash__(self): + return hash("CreateApi") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "apiId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.CreateApiRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.Api: + r"""Call the create api method over HTTP. + + Args: + request (~.registry_service.CreateApiRequest): + The request object. Request message for CreateApi. + 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: + ~.registry_models.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/apis', + 'body': 'api', + }, + ] + request, metadata = self._interceptor.pre_create_api(request, metadata) + pb_request = registry_service.CreateApiRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.Api() + pb_resp = registry_models.Api.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_api(resp) + return resp + + class _CreateApiDeployment(RegistryRestStub): + def __hash__(self): + return hash("CreateApiDeployment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "apiDeploymentId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.CreateApiDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiDeployment: + r"""Call the create api deployment method over HTTP. + + Args: + request (~.registry_service.CreateApiDeploymentRequest): + The request object. Request message for + CreateApiDeployment. + + 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: + ~.registry_models.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/deployments', + 'body': 'api_deployment', + }, + ] + request, metadata = self._interceptor.pre_create_api_deployment(request, metadata) + pb_request = registry_service.CreateApiDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiDeployment() + pb_resp = registry_models.ApiDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_api_deployment(resp) + return resp + + class _CreateApiSpec(RegistryRestStub): + def __hash__(self): + return hash("CreateApiSpec") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "apiSpecId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.CreateApiSpecRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiSpec: + r"""Call the create api spec method over HTTP. + + Args: + request (~.registry_service.CreateApiSpecRequest): + The request object. Request message for CreateApiSpec. + 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: + ~.registry_models.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs', + 'body': 'api_spec', + }, + ] + request, metadata = self._interceptor.pre_create_api_spec(request, metadata) + pb_request = registry_service.CreateApiSpecRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiSpec() + pb_resp = registry_models.ApiSpec.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_api_spec(resp) + return resp + + class _CreateApiVersion(RegistryRestStub): + def __hash__(self): + return hash("CreateApiVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "apiVersionId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.CreateApiVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiVersion: + r"""Call the create api version method over HTTP. + + Args: + request (~.registry_service.CreateApiVersionRequest): + The request object. Request message for CreateApiVersion. + 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: + ~.registry_models.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/versions', + 'body': 'api_version', + }, + ] + request, metadata = self._interceptor.pre_create_api_version(request, metadata) + pb_request = registry_service.CreateApiVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiVersion() + pb_resp = registry_models.ApiVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_api_version(resp) + return resp + + class _CreateArtifact(RegistryRestStub): + def __hash__(self): + return hash("CreateArtifact") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "artifactId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.CreateArtifactRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.Artifact: + r"""Call the create artifact method over HTTP. + + Args: + request (~.registry_service.CreateArtifactRequest): + The request object. Request message for CreateArtifact. + 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: + ~.registry_models.Artifact: + Artifacts of resources. Artifacts are unique + (single-value) per resource and are used to store + metadata that is too large or numerous to be stored + directly on the resource. Since artifacts are stored + separately from parent resources, they should generally + be used for metadata that is needed infrequently, i.e., + not for display in primary views of the resource but + perhaps displayed or downloaded upon request. The + ``ListArtifacts`` method allows artifacts to be quickly + enumerated and checked for presence without downloading + their (potentially-large) contents. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/artifacts', + 'body': 'artifact', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/artifacts', + 'body': 'artifact', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/artifacts', + 'body': 'artifact', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*/specs/*}/artifacts', + 'body': 'artifact', + }, +{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/deployments/*}/artifacts', + 'body': 'artifact', + }, + ] + request, metadata = self._interceptor.pre_create_artifact(request, metadata) + pb_request = registry_service.CreateArtifactRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.Artifact() + pb_resp = registry_models.Artifact.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_artifact(resp) + return resp + + class _DeleteApi(RegistryRestStub): + def __hash__(self): + return hash("DeleteApi") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.DeleteApiRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete api method over HTTP. + + Args: + request (~.registry_service.DeleteApiRequest): + The request object. Request message for DeleteApi. + 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_api(request, metadata) + pb_request = registry_service.DeleteApiRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteApiDeployment(RegistryRestStub): + def __hash__(self): + return hash("DeleteApiDeployment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.DeleteApiDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete api deployment method over HTTP. + + Args: + request (~.registry_service.DeleteApiDeploymentRequest): + The request object. Request message for + DeleteApiDeployment. + + 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_api_deployment(request, metadata) + pb_request = registry_service.DeleteApiDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteApiDeploymentRevision(RegistryRestStub): + def __hash__(self): + return hash("DeleteApiDeploymentRevision") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.DeleteApiDeploymentRevisionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiDeployment: + r"""Call the delete api deployment + revision method over HTTP. + + Args: + request (~.registry_service.DeleteApiDeploymentRevisionRequest): + The request object. Request message for + DeleteApiDeploymentRevision. + + 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: + ~.registry_models.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:deleteRevision', + }, + ] + request, metadata = self._interceptor.pre_delete_api_deployment_revision(request, metadata) + pb_request = registry_service.DeleteApiDeploymentRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiDeployment() + pb_resp = registry_models.ApiDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_api_deployment_revision(resp) + return resp + + class _DeleteApiSpec(RegistryRestStub): + def __hash__(self): + return hash("DeleteApiSpec") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.DeleteApiSpecRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete api spec method over HTTP. + + Args: + request (~.registry_service.DeleteApiSpecRequest): + The request object. Request message for DeleteApiSpec. + 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_api_spec(request, metadata) + pb_request = registry_service.DeleteApiSpecRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteApiSpecRevision(RegistryRestStub): + def __hash__(self): + return hash("DeleteApiSpecRevision") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.DeleteApiSpecRevisionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiSpec: + r"""Call the delete api spec revision method over HTTP. + + Args: + request (~.registry_service.DeleteApiSpecRevisionRequest): + The request object. Request message for + DeleteApiSpecRevision. + + 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: + ~.registry_models.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:deleteRevision', + }, + ] + request, metadata = self._interceptor.pre_delete_api_spec_revision(request, metadata) + pb_request = registry_service.DeleteApiSpecRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiSpec() + pb_resp = registry_models.ApiSpec.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_delete_api_spec_revision(resp) + return resp + + class _DeleteApiVersion(RegistryRestStub): + def __hash__(self): + return hash("DeleteApiVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.DeleteApiVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete api version method over HTTP. + + Args: + request (~.registry_service.DeleteApiVersionRequest): + The request object. Request message for DeleteApiVersion. + 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_api_version(request, metadata) + pb_request = registry_service.DeleteApiVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteArtifact(RegistryRestStub): + def __hash__(self): + return hash("DeleteArtifact") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.DeleteArtifactRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete artifact method over HTTP. + + Args: + request (~.registry_service.DeleteArtifactRequest): + The request object. Request message for DeleteArtifact. + 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/artifacts/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/artifacts/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/artifacts/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}', + }, +{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_artifact(request, metadata) + pb_request = registry_service.DeleteArtifactRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetApi(RegistryRestStub): + def __hash__(self): + return hash("GetApi") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.GetApiRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.Api: + r"""Call the get api method over HTTP. + + Args: + request (~.registry_service.GetApiRequest): + The request object. Request message for GetApi. + 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: + ~.registry_models.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*}', + }, + ] + request, metadata = self._interceptor.pre_get_api(request, metadata) + pb_request = registry_service.GetApiRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.Api() + pb_resp = registry_models.Api.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_api(resp) + return resp + + class _GetApiDeployment(RegistryRestStub): + def __hash__(self): + return hash("GetApiDeployment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.GetApiDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiDeployment: + r"""Call the get api deployment method over HTTP. + + Args: + request (~.registry_service.GetApiDeploymentRequest): + The request object. Request message for GetApiDeployment. + 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: + ~.registry_models.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}', + }, + ] + request, metadata = self._interceptor.pre_get_api_deployment(request, metadata) + pb_request = registry_service.GetApiDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiDeployment() + pb_resp = registry_models.ApiDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_api_deployment(resp) + return resp + + class _GetApiSpec(RegistryRestStub): + def __hash__(self): + return hash("GetApiSpec") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.GetApiSpecRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiSpec: + r"""Call the get api spec method over HTTP. + + Args: + request (~.registry_service.GetApiSpecRequest): + The request object. Request message for GetApiSpec. + 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: + ~.registry_models.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}', + }, + ] + request, metadata = self._interceptor.pre_get_api_spec(request, metadata) + pb_request = registry_service.GetApiSpecRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiSpec() + pb_resp = registry_models.ApiSpec.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_api_spec(resp) + return resp + + class _GetApiSpecContents(RegistryRestStub): + def __hash__(self): + return hash("GetApiSpecContents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.GetApiSpecContentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> httpbody_pb2.HttpBody: + r"""Call the get api spec contents method over HTTP. + + Args: + request (~.registry_service.GetApiSpecContentsRequest): + The request object. Request message for + GetApiSpecContents. + + 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: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:getContents', + }, + ] + request, metadata = self._interceptor.pre_get_api_spec_contents(request, metadata) + pb_request = registry_service.GetApiSpecContentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_api_spec_contents(resp) + return resp + + class _GetApiVersion(RegistryRestStub): + def __hash__(self): + return hash("GetApiVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.GetApiVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiVersion: + r"""Call the get api version method over HTTP. + + Args: + request (~.registry_service.GetApiVersionRequest): + The request object. Request message for GetApiVersion. + 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: + ~.registry_models.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*}', + }, + ] + request, metadata = self._interceptor.pre_get_api_version(request, metadata) + pb_request = registry_service.GetApiVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiVersion() + pb_resp = registry_models.ApiVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_api_version(resp) + return resp + + class _GetArtifact(RegistryRestStub): + def __hash__(self): + return hash("GetArtifact") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.GetArtifactRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.Artifact: + r"""Call the get artifact method over HTTP. + + Args: + request (~.registry_service.GetArtifactRequest): + The request object. Request message for GetArtifact. + 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: + ~.registry_models.Artifact: + Artifacts of resources. Artifacts are unique + (single-value) per resource and are used to store + metadata that is too large or numerous to be stored + directly on the resource. Since artifacts are stored + separately from parent resources, they should generally + be used for metadata that is needed infrequently, i.e., + not for display in primary views of the resource but + perhaps displayed or downloaded upon request. The + ``ListArtifacts`` method allows artifacts to be quickly + enumerated and checked for presence without downloading + their (potentially-large) contents. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/artifacts/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/artifacts/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/artifacts/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}', + }, + ] + request, metadata = self._interceptor.pre_get_artifact(request, metadata) + pb_request = registry_service.GetArtifactRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.Artifact() + pb_resp = registry_models.Artifact.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_artifact(resp) + return resp + + class _GetArtifactContents(RegistryRestStub): + def __hash__(self): + return hash("GetArtifactContents") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.GetArtifactContentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> httpbody_pb2.HttpBody: + r"""Call the get artifact contents method over HTTP. + + Args: + request (~.registry_service.GetArtifactContentsRequest): + The request object. Request message for + GetArtifactContents. + + 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: + ~.httpbody_pb2.HttpBody: + Message that represents an arbitrary HTTP body. It + should only be used for payload formats that can't be + represented as JSON, such as raw binary or an HTML page. + + This message can be used both in streaming and + non-streaming API methods in the request as well as the + response. + + It can be used as a top-level request field, which is + convenient if one wants to extract parameters from + either the URL or HTTP template into the request fields + and also want access to the raw HTTP body. + + Example: + + :: + + message GetResourceRequest { + // A unique request id. + string request_id = 1; + + // The raw HTTP body is bound to this field. + google.api.HttpBody http_body = 2; + + } + + service ResourceService { + rpc GetResource(GetResourceRequest) + returns (google.api.HttpBody); + rpc UpdateResource(google.api.HttpBody) + returns (google.protobuf.Empty); + + } + + Example with streaming methods: + + :: + + service CaldavService { + rpc GetCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + rpc UpdateCalendar(stream google.api.HttpBody) + returns (stream google.api.HttpBody); + + } + + Use of this type only changes how the request and + response bodies are handled, all other features will + continue to work unchanged. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/artifacts/*}:getContents', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/artifacts/*}:getContents', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/artifacts/*}:getContents', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:getContents', + }, +{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}:getContents', + }, + ] + request, metadata = self._interceptor.pre_get_artifact_contents(request, metadata) + pb_request = registry_service.GetArtifactContentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = httpbody_pb2.HttpBody() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_artifact_contents(resp) + return resp + + class _ListApiDeploymentRevisions(RegistryRestStub): + def __hash__(self): + return hash("ListApiDeploymentRevisions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ListApiDeploymentRevisionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_service.ListApiDeploymentRevisionsResponse: + r"""Call the list api deployment + revisions method over HTTP. + + Args: + request (~.registry_service.ListApiDeploymentRevisionsRequest): + The request object. Request message for + ListApiDeploymentRevisions. + + 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: + ~.registry_service.ListApiDeploymentRevisionsResponse: + Response message for + ListApiDeploymentRevisionsResponse. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:listRevisions', + }, + ] + request, metadata = self._interceptor.pre_list_api_deployment_revisions(request, metadata) + pb_request = registry_service.ListApiDeploymentRevisionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_service.ListApiDeploymentRevisionsResponse() + pb_resp = registry_service.ListApiDeploymentRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_api_deployment_revisions(resp) + return resp + + class _ListApiDeployments(RegistryRestStub): + def __hash__(self): + return hash("ListApiDeployments") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ListApiDeploymentsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_service.ListApiDeploymentsResponse: + r"""Call the list api deployments method over HTTP. + + Args: + request (~.registry_service.ListApiDeploymentsRequest): + The request object. Request message for + ListApiDeployments. + + 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: + ~.registry_service.ListApiDeploymentsResponse: + Response message for + ListApiDeployments. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/deployments', + }, + ] + request, metadata = self._interceptor.pre_list_api_deployments(request, metadata) + pb_request = registry_service.ListApiDeploymentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_service.ListApiDeploymentsResponse() + pb_resp = registry_service.ListApiDeploymentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_api_deployments(resp) + return resp + + class _ListApis(RegistryRestStub): + def __hash__(self): + return hash("ListApis") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ListApisRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_service.ListApisResponse: + r"""Call the list apis method over HTTP. + + Args: + request (~.registry_service.ListApisRequest): + The request object. Request message for ListApis. + 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: + ~.registry_service.ListApisResponse: + Response message for ListApis. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/apis', + }, + ] + request, metadata = self._interceptor.pre_list_apis(request, metadata) + pb_request = registry_service.ListApisRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_service.ListApisResponse() + pb_resp = registry_service.ListApisResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_apis(resp) + return resp + + class _ListApiSpecRevisions(RegistryRestStub): + def __hash__(self): + return hash("ListApiSpecRevisions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ListApiSpecRevisionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_service.ListApiSpecRevisionsResponse: + r"""Call the list api spec revisions method over HTTP. + + Args: + request (~.registry_service.ListApiSpecRevisionsRequest): + The request object. Request message for + ListApiSpecRevisions. + + 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: + ~.registry_service.ListApiSpecRevisionsResponse: + Response message for + ListApiSpecRevisionsResponse. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:listRevisions', + }, + ] + request, metadata = self._interceptor.pre_list_api_spec_revisions(request, metadata) + pb_request = registry_service.ListApiSpecRevisionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_service.ListApiSpecRevisionsResponse() + pb_resp = registry_service.ListApiSpecRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_api_spec_revisions(resp) + return resp + + class _ListApiSpecs(RegistryRestStub): + def __hash__(self): + return hash("ListApiSpecs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ListApiSpecsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_service.ListApiSpecsResponse: + r"""Call the list api specs method over HTTP. + + Args: + request (~.registry_service.ListApiSpecsRequest): + The request object. Request message for ListApiSpecs. + 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: + ~.registry_service.ListApiSpecsResponse: + Response message for ListApiSpecs. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs', + }, + ] + request, metadata = self._interceptor.pre_list_api_specs(request, metadata) + pb_request = registry_service.ListApiSpecsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_service.ListApiSpecsResponse() + pb_resp = registry_service.ListApiSpecsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_api_specs(resp) + return resp + + class _ListApiVersions(RegistryRestStub): + def __hash__(self): + return hash("ListApiVersions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ListApiVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_service.ListApiVersionsResponse: + r"""Call the list api versions method over HTTP. + + Args: + request (~.registry_service.ListApiVersionsRequest): + The request object. Request message for ListApiVersions. + 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: + ~.registry_service.ListApiVersionsResponse: + Response message for ListApiVersions. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/versions', + }, + ] + request, metadata = self._interceptor.pre_list_api_versions(request, metadata) + pb_request = registry_service.ListApiVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_service.ListApiVersionsResponse() + pb_resp = registry_service.ListApiVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_api_versions(resp) + return resp + + class _ListArtifacts(RegistryRestStub): + def __hash__(self): + return hash("ListArtifacts") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ListArtifactsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_service.ListArtifactsResponse: + r"""Call the list artifacts method over HTTP. + + Args: + request (~.registry_service.ListArtifactsRequest): + The request object. Request message for ListArtifacts. + 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: + ~.registry_service.ListArtifactsResponse: + Response message for ListArtifacts. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/artifacts', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/artifacts', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/artifacts', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*/specs/*}/artifacts', + }, +{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/apis/*/deployments/*}/artifacts', + }, + ] + request, metadata = self._interceptor.pre_list_artifacts(request, metadata) + pb_request = registry_service.ListArtifactsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_service.ListArtifactsResponse() + pb_resp = registry_service.ListArtifactsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_artifacts(resp) + return resp + + class _ReplaceArtifact(RegistryRestStub): + def __hash__(self): + return hash("ReplaceArtifact") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.ReplaceArtifactRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.Artifact: + r"""Call the replace artifact method over HTTP. + + Args: + request (~.registry_service.ReplaceArtifactRequest): + The request object. Request message for ReplaceArtifact. + 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: + ~.registry_models.Artifact: + Artifacts of resources. Artifacts are unique + (single-value) per resource and are used to store + metadata that is too large or numerous to be stored + directly on the resource. Since artifacts are stored + separately from parent resources, they should generally + be used for metadata that is needed infrequently, i.e., + not for display in primary views of the resource but + perhaps displayed or downloaded upon request. The + ``ListArtifacts`` method allows artifacts to be quickly + enumerated and checked for presence without downloading + their (potentially-large) contents. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'put', + 'uri': '/v1/{artifact.name=projects/*/locations/*/artifacts/*}', + 'body': 'artifact', + }, +{ + 'method': 'put', + 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/artifacts/*}', + 'body': 'artifact', + }, +{ + 'method': 'put', + 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/versions/*/artifacts/*}', + 'body': 'artifact', + }, +{ + 'method': 'put', + 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}', + 'body': 'artifact', + }, +{ + 'method': 'put', + 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}', + 'body': 'artifact', + }, + ] + request, metadata = self._interceptor.pre_replace_artifact(request, metadata) + pb_request = registry_service.ReplaceArtifactRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.Artifact() + pb_resp = registry_models.Artifact.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_replace_artifact(resp) + return resp + + class _RollbackApiDeployment(RegistryRestStub): + def __hash__(self): + return hash("RollbackApiDeployment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.RollbackApiDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiDeployment: + r"""Call the rollback api deployment method over HTTP. + + Args: + request (~.registry_service.RollbackApiDeploymentRequest): + The request object. Request message for + RollbackApiDeployment. + + 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: + ~.registry_models.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:rollback', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_rollback_api_deployment(request, metadata) + pb_request = registry_service.RollbackApiDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiDeployment() + pb_resp = registry_models.ApiDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_rollback_api_deployment(resp) + return resp + + class _RollbackApiSpec(RegistryRestStub): + def __hash__(self): + return hash("RollbackApiSpec") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.RollbackApiSpecRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiSpec: + r"""Call the rollback api spec method over HTTP. + + Args: + request (~.registry_service.RollbackApiSpecRequest): + The request object. Request message for RollbackApiSpec. + 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: + ~.registry_models.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:rollback', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_rollback_api_spec(request, metadata) + pb_request = registry_service.RollbackApiSpecRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiSpec() + pb_resp = registry_models.ApiSpec.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_rollback_api_spec(resp) + return resp + + class _TagApiDeploymentRevision(RegistryRestStub): + def __hash__(self): + return hash("TagApiDeploymentRevision") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.TagApiDeploymentRevisionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiDeployment: + r"""Call the tag api deployment + revision method over HTTP. + + Args: + request (~.registry_service.TagApiDeploymentRevisionRequest): + The request object. Request message for + TagApiDeploymentRevision. + + 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: + ~.registry_models.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:tagRevision', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_tag_api_deployment_revision(request, metadata) + pb_request = registry_service.TagApiDeploymentRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiDeployment() + pb_resp = registry_models.ApiDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_tag_api_deployment_revision(resp) + return resp + + class _TagApiSpecRevision(RegistryRestStub): + def __hash__(self): + return hash("TagApiSpecRevision") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.TagApiSpecRevisionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiSpec: + r"""Call the tag api spec revision method over HTTP. + + Args: + request (~.registry_service.TagApiSpecRevisionRequest): + The request object. Request message for + TagApiSpecRevision. + + 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: + ~.registry_models.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:tagRevision', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_tag_api_spec_revision(request, metadata) + pb_request = registry_service.TagApiSpecRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiSpec() + pb_resp = registry_models.ApiSpec.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_tag_api_spec_revision(resp) + return resp + + class _UpdateApi(RegistryRestStub): + def __hash__(self): + return hash("UpdateApi") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.UpdateApiRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.Api: + r"""Call the update api method over HTTP. + + Args: + request (~.registry_service.UpdateApiRequest): + The request object. Request message for UpdateApi. + 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: + ~.registry_models.Api: + A top-level description of an API. + Produced by producers and are + commitments to provide services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{api.name=projects/*/locations/*/apis/*}', + 'body': 'api', + }, + ] + request, metadata = self._interceptor.pre_update_api(request, metadata) + pb_request = registry_service.UpdateApiRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.Api() + pb_resp = registry_models.Api.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_api(resp) + return resp + + class _UpdateApiDeployment(RegistryRestStub): + def __hash__(self): + return hash("UpdateApiDeployment") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.UpdateApiDeploymentRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiDeployment: + r"""Call the update api deployment method over HTTP. + + Args: + request (~.registry_service.UpdateApiDeploymentRequest): + The request object. Request message for + UpdateApiDeployment. + + 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: + ~.registry_models.ApiDeployment: + Describes a service running at + particular address that provides a + particular version of an API. + ApiDeployments have revisions which + correspond to different configurations + of a single deployment in time. Revision + identifiers should be updated whenever + the served API spec or endpoint address + changes. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{api_deployment.name=projects/*/locations/*/apis/*/deployments/*}', + 'body': 'api_deployment', + }, + ] + request, metadata = self._interceptor.pre_update_api_deployment(request, metadata) + pb_request = registry_service.UpdateApiDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiDeployment() + pb_resp = registry_models.ApiDeployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_api_deployment(resp) + return resp + + class _UpdateApiSpec(RegistryRestStub): + def __hash__(self): + return hash("UpdateApiSpec") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.UpdateApiSpecRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiSpec: + r"""Call the update api spec method over HTTP. + + Args: + request (~.registry_service.UpdateApiSpecRequest): + The request object. Request message for UpdateApiSpec. + 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: + ~.registry_models.ApiSpec: + Describes a version of an API in a + structured way. ApiSpecs provide formal + descriptions that consumers can use to + use a version. ApiSpec resources are + intended to be fully-resolved + descriptions of an ApiVersion. When + specs consist of multiple files, these + should be bundled together (e.g., in a + zip archive) and stored as a unit. + Multiple specs can exist to provide + representations in different API + description formats. Synchronization of + these representations would be provided + by tooling and background services. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{api_spec.name=projects/*/locations/*/apis/*/versions/*/specs/*}', + 'body': 'api_spec', + }, + ] + request, metadata = self._interceptor.pre_update_api_spec(request, metadata) + pb_request = registry_service.UpdateApiSpecRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiSpec() + pb_resp = registry_models.ApiSpec.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_api_spec(resp) + return resp + + class _UpdateApiVersion(RegistryRestStub): + def __hash__(self): + return hash("UpdateApiVersion") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + def __call__(self, + request: registry_service.UpdateApiVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> registry_models.ApiVersion: + r"""Call the update api version method over HTTP. + + Args: + request (~.registry_service.UpdateApiVersionRequest): + The request object. Request message for UpdateApiVersion. + 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: + ~.registry_models.ApiVersion: + Describes a particular version of an + API. ApiVersions are what consumers + actually use. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{api_version.name=projects/*/locations/*/apis/*/versions/*}', + 'body': 'api_version', + }, + ] + request, metadata = self._interceptor.pre_update_api_version(request, metadata) + pb_request = registry_service.UpdateApiVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + including_default_value_fields=False, + use_integers_for_enums=True + ) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + including_default_value_fields=False, + use_integers_for_enums=True, + )) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = registry_models.ApiVersion() + pb_resp = registry_models.ApiVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_api_version(resp) + return resp + + @property + def create_api(self) -> Callable[ + [registry_service.CreateApiRequest], + registry_models.Api]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_api_deployment(self) -> Callable[ + [registry_service.CreateApiDeploymentRequest], + registry_models.ApiDeployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApiDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_api_spec(self) -> Callable[ + [registry_service.CreateApiSpecRequest], + registry_models.ApiSpec]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApiSpec(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_api_version(self) -> Callable[ + [registry_service.CreateApiVersionRequest], + registry_models.ApiVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApiVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_artifact(self) -> Callable[ + [registry_service.CreateArtifactRequest], + registry_models.Artifact]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateArtifact(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api(self) -> Callable[ + [registry_service.DeleteApiRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api_deployment(self) -> Callable[ + [registry_service.DeleteApiDeploymentRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApiDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api_deployment_revision(self) -> Callable[ + [registry_service.DeleteApiDeploymentRevisionRequest], + registry_models.ApiDeployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApiDeploymentRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api_spec(self) -> Callable[ + [registry_service.DeleteApiSpecRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApiSpec(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api_spec_revision(self) -> Callable[ + [registry_service.DeleteApiSpecRevisionRequest], + registry_models.ApiSpec]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApiSpecRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_api_version(self) -> Callable[ + [registry_service.DeleteApiVersionRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApiVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_artifact(self) -> Callable[ + [registry_service.DeleteArtifactRequest], + empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteArtifact(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_api(self) -> Callable[ + [registry_service.GetApiRequest], + registry_models.Api]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_api_deployment(self) -> Callable[ + [registry_service.GetApiDeploymentRequest], + registry_models.ApiDeployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApiDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_api_spec(self) -> Callable[ + [registry_service.GetApiSpecRequest], + registry_models.ApiSpec]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApiSpec(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_api_spec_contents(self) -> Callable[ + [registry_service.GetApiSpecContentsRequest], + httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApiSpecContents(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_api_version(self) -> Callable[ + [registry_service.GetApiVersionRequest], + registry_models.ApiVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApiVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_artifact(self) -> Callable[ + [registry_service.GetArtifactRequest], + registry_models.Artifact]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetArtifact(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_artifact_contents(self) -> Callable[ + [registry_service.GetArtifactContentsRequest], + httpbody_pb2.HttpBody]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetArtifactContents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_api_deployment_revisions(self) -> Callable[ + [registry_service.ListApiDeploymentRevisionsRequest], + registry_service.ListApiDeploymentRevisionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApiDeploymentRevisions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_api_deployments(self) -> Callable[ + [registry_service.ListApiDeploymentsRequest], + registry_service.ListApiDeploymentsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApiDeployments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_apis(self) -> Callable[ + [registry_service.ListApisRequest], + registry_service.ListApisResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApis(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_api_spec_revisions(self) -> Callable[ + [registry_service.ListApiSpecRevisionsRequest], + registry_service.ListApiSpecRevisionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApiSpecRevisions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_api_specs(self) -> Callable[ + [registry_service.ListApiSpecsRequest], + registry_service.ListApiSpecsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApiSpecs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_api_versions(self) -> Callable[ + [registry_service.ListApiVersionsRequest], + registry_service.ListApiVersionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApiVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_artifacts(self) -> Callable[ + [registry_service.ListArtifactsRequest], + registry_service.ListArtifactsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListArtifacts(self._session, self._host, self._interceptor) # type: ignore + + @property + def replace_artifact(self) -> Callable[ + [registry_service.ReplaceArtifactRequest], + registry_models.Artifact]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReplaceArtifact(self._session, self._host, self._interceptor) # type: ignore + + @property + def rollback_api_deployment(self) -> Callable[ + [registry_service.RollbackApiDeploymentRequest], + registry_models.ApiDeployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RollbackApiDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def rollback_api_spec(self) -> Callable[ + [registry_service.RollbackApiSpecRequest], + registry_models.ApiSpec]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RollbackApiSpec(self._session, self._host, self._interceptor) # type: ignore + + @property + def tag_api_deployment_revision(self) -> Callable[ + [registry_service.TagApiDeploymentRevisionRequest], + registry_models.ApiDeployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TagApiDeploymentRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def tag_api_spec_revision(self) -> Callable[ + [registry_service.TagApiSpecRevisionRequest], + registry_models.ApiSpec]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TagApiSpecRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_api(self) -> Callable[ + [registry_service.UpdateApiRequest], + registry_models.Api]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApi(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_api_deployment(self) -> Callable[ + [registry_service.UpdateApiDeploymentRequest], + registry_models.ApiDeployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApiDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_api_spec(self) -> Callable[ + [registry_service.UpdateApiSpecRequest], + registry_models.ApiSpec]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApiSpec(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_api_version(self) -> Callable[ + [registry_service.UpdateApiVersionRequest], + registry_models.ApiVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApiVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(RegistryRestStub): + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object 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: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_location(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.Location() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(RegistryRestStub): + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object 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: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(RegistryRestStub): + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:getIamPolicy', + }, +{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/runtime}:getIamPolicy', + }, + ] + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(RegistryRestStub): + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:setIamPolicy', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/runtime}:setIamPolicy', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request['body'])) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = policy_pb2.Policy() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(RegistryRestStub): + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:testIamPermissions', + 'body': '*', + }, +{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/runtime}:testIamPermissions', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request['body'])) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation(RegistryRestStub): + def __call__(self, + request: operations_pb2.CancelOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', + 'body': '*', + }, + ] + + request, metadata = self._interceptor.pre_cancel_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + body = json.loads(json.dumps(transcoded_request['body'])) + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation(RegistryRestStub): + def __call__(self, + request: operations_pb2.DeleteOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> None: + + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object 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. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_delete_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(RegistryRestStub): + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object 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: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations(RegistryRestStub): + def __call__(self, + request: operations_pb2.ListOperationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.ListOperationsResponse: + + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object 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 from ListOperations method. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}/operations', + }, + ] + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + + # Send the request + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_list_operations(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'RegistryRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py new file mode 100644 index 0000000..0471a2f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py @@ -0,0 +1,128 @@ +# -*- 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. +# +from .provisioning_service import ( + CreateInstanceRequest, + DeleteInstanceRequest, + GetInstanceRequest, + Instance, + OperationMetadata, +) +from .registry_models import ( + Api, + ApiDeployment, + ApiSpec, + ApiVersion, + Artifact, +) +from .registry_service import ( + CreateApiDeploymentRequest, + CreateApiRequest, + CreateApiSpecRequest, + CreateApiVersionRequest, + CreateArtifactRequest, + DeleteApiDeploymentRequest, + DeleteApiDeploymentRevisionRequest, + DeleteApiRequest, + DeleteApiSpecRequest, + DeleteApiSpecRevisionRequest, + DeleteApiVersionRequest, + DeleteArtifactRequest, + GetApiDeploymentRequest, + GetApiRequest, + GetApiSpecContentsRequest, + GetApiSpecRequest, + GetApiVersionRequest, + GetArtifactContentsRequest, + GetArtifactRequest, + ListApiDeploymentRevisionsRequest, + ListApiDeploymentRevisionsResponse, + ListApiDeploymentsRequest, + ListApiDeploymentsResponse, + ListApiSpecRevisionsRequest, + ListApiSpecRevisionsResponse, + ListApiSpecsRequest, + ListApiSpecsResponse, + ListApisRequest, + ListApisResponse, + ListApiVersionsRequest, + ListApiVersionsResponse, + ListArtifactsRequest, + ListArtifactsResponse, + ReplaceArtifactRequest, + RollbackApiDeploymentRequest, + RollbackApiSpecRequest, + TagApiDeploymentRevisionRequest, + TagApiSpecRevisionRequest, + UpdateApiDeploymentRequest, + UpdateApiRequest, + UpdateApiSpecRequest, + UpdateApiVersionRequest, +) + +__all__ = ( + 'CreateInstanceRequest', + 'DeleteInstanceRequest', + 'GetInstanceRequest', + 'Instance', + 'OperationMetadata', + 'Api', + 'ApiDeployment', + 'ApiSpec', + 'ApiVersion', + 'Artifact', + 'CreateApiDeploymentRequest', + 'CreateApiRequest', + 'CreateApiSpecRequest', + 'CreateApiVersionRequest', + 'CreateArtifactRequest', + 'DeleteApiDeploymentRequest', + 'DeleteApiDeploymentRevisionRequest', + 'DeleteApiRequest', + 'DeleteApiSpecRequest', + 'DeleteApiSpecRevisionRequest', + 'DeleteApiVersionRequest', + 'DeleteArtifactRequest', + 'GetApiDeploymentRequest', + 'GetApiRequest', + 'GetApiSpecContentsRequest', + 'GetApiSpecRequest', + 'GetApiVersionRequest', + 'GetArtifactContentsRequest', + 'GetArtifactRequest', + 'ListApiDeploymentRevisionsRequest', + 'ListApiDeploymentRevisionsResponse', + 'ListApiDeploymentsRequest', + 'ListApiDeploymentsResponse', + 'ListApiSpecRevisionsRequest', + 'ListApiSpecRevisionsResponse', + 'ListApiSpecsRequest', + 'ListApiSpecsResponse', + 'ListApisRequest', + 'ListApisResponse', + 'ListApiVersionsRequest', + 'ListApiVersionsResponse', + 'ListArtifactsRequest', + 'ListArtifactsResponse', + 'ReplaceArtifactRequest', + 'RollbackApiDeploymentRequest', + 'RollbackApiSpecRequest', + 'TagApiDeploymentRevisionRequest', + 'TagApiSpecRevisionRequest', + 'UpdateApiDeploymentRequest', + 'UpdateApiRequest', + 'UpdateApiSpecRequest', + 'UpdateApiVersionRequest', +) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py new file mode 100644 index 0000000..9ed2198 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py @@ -0,0 +1,262 @@ +# -*- 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.apigeeregistry.v1', + manifest={ + 'CreateInstanceRequest', + 'DeleteInstanceRequest', + 'GetInstanceRequest', + 'OperationMetadata', + 'Instance', + }, +) + + +class CreateInstanceRequest(proto.Message): + r"""Request message for CreateInstance. + + Attributes: + parent (str): + Required. Parent resource of the Instance, of the form: + ``projects/*/locations/*`` + instance_id (str): + Required. Identifier to assign to the + Instance. Must be unique within scope of the + parent resource. + instance (google.cloud.apigee_registry_v1.types.Instance): + Required. The Instance. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: 'Instance' = proto.Field( + proto.MESSAGE, + number=3, + message='Instance', + ) + + +class DeleteInstanceRequest(proto.Message): + r"""Request message for DeleteInstance. + + Attributes: + name (str): + Required. The name of the Instance to delete. Format: + ``projects/*/locations/*/instances/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetInstanceRequest(proto.Message): + r"""Request message for GetInstance. + + Attributes: + name (str): + Required. The name of the Instance to retrieve. Format: + ``projects/*/locations/*/instances/*``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation was created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the operation finished running. + target (str): + Server-defined resource path for the target + of the operation. + verb (str): + Name of the verb executed by the operation. + status_message (str): + Human-readable status of the operation, if + any. + cancellation_requested (bool): + Identifies whether the user has requested cancellation of + the operation. Operations that have successfully been + cancelled have [Operation.error][] value with a + [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to ``Code.CANCELLED``. + api_version (str): + API version used to start the operation. + """ + + create_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, + ) + target: str = proto.Field( + proto.STRING, + number=3, + ) + verb: str = proto.Field( + proto.STRING, + number=4, + ) + status_message: str = proto.Field( + proto.STRING, + number=5, + ) + cancellation_requested: bool = proto.Field( + proto.BOOL, + number=6, + ) + api_version: str = proto.Field( + proto.STRING, + number=7, + ) + + +class Instance(proto.Message): + r"""An Instance represents the instance resources of the + Registry. Currently, only one instance is allowed for each + project. + + Attributes: + name (str): + Format: ``projects/*/locations/*/instance``. Currently only + ``locations/global`` is supported. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update timestamp. + state (google.cloud.apigee_registry_v1.types.Instance.State): + Output only. The current state of the + Instance. + state_message (str): + Output only. Extra information of Instance.State if the + state is ``FAILED``. + config (google.cloud.apigee_registry_v1.types.Instance.Config): + Required. Config of the Instance. + """ + class State(proto.Enum): + r"""State of the Instance. + + Values: + STATE_UNSPECIFIED (0): + The default value. This value is used if the + state is omitted. + INACTIVE (1): + The Instance has not been initialized or has + been deleted. + CREATING (2): + The Instance is being created. + ACTIVE (3): + The Instance has been created and is ready + for use. + UPDATING (4): + The Instance is being updated. + DELETING (5): + The Instance is being deleted. + FAILED (6): + The Instance encountered an error during a + state change. + """ + STATE_UNSPECIFIED = 0 + INACTIVE = 1 + CREATING = 2 + ACTIVE = 3 + UPDATING = 4 + DELETING = 5 + FAILED = 6 + + class Config(proto.Message): + r"""Available configurations to provision an Instance. + + Attributes: + location (str): + Output only. The GCP location where the + Instance resides. + cmek_key_name (str): + Required. The Customer Managed Encryption Key (CMEK) used + for data encryption. The CMEK name should follow the format + of + ``projects/([^/]+)/locations/([^/]+)/keyRings/([^/]+)/cryptoKeys/([^/]+)``, + where the ``location`` must match InstanceConfig.location. + """ + + location: str = proto.Field( + proto.STRING, + number=1, + ) + cmek_key_name: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + state_message: str = proto.Field( + proto.STRING, + number=5, + ) + config: Config = proto.Field( + proto.MESSAGE, + number=6, + message=Config, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py new file mode 100644 index 0000000..34991bd --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py @@ -0,0 +1,573 @@ +# -*- 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.apigeeregistry.v1', + manifest={ + 'Api', + 'ApiVersion', + 'ApiSpec', + 'ApiDeployment', + 'Artifact', + }, +) + + +class Api(proto.Message): + r"""A top-level description of an API. + Produced by producers and are commitments to provide services. + + Attributes: + name (str): + Resource name. + display_name (str): + Human-meaningful name. + description (str): + A detailed description. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update timestamp. + availability (str): + A user-definable description of the + availability of this service. Format: free-form, + but we expect single words that describe + availability, e.g., "NONE", "TESTING", + "PREVIEW", "GENERAL", "DEPRECATED", "SHUTDOWN". + recommended_version (str): + The recommended version of the API. Format: + ``apis/{api}/versions/{version}`` + recommended_deployment (str): + The recommended deployment of the API. Format: + ``apis/{api}/deployments/{deployment}`` + labels (MutableMapping[str, str]): + Labels attach identifying metadata to resources. Identifying + metadata can be used to filter list operations. + + Label keys and values can be no longer than 64 characters + (Unicode codepoints), can only contain lowercase letters, + numeric characters, underscores, and dashes. International + characters are allowed. No more than 64 user labels can be + associated with one resource (System labels are excluded). + + See https://goo.gl/xmQnxf for more information and examples + of labels. System reserved label keys are prefixed with + ``apigeeregistry.googleapis.com/`` and cannot be changed. + annotations (MutableMapping[str, str]): + Annotations attach non-identifying metadata + to resources. + Annotation keys and values are less restricted + than those of labels, but should be generally + used for small values of broad interest. Larger, + topic- specific metadata should be stored in + Artifacts. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + availability: str = proto.Field( + proto.STRING, + number=6, + ) + recommended_version: str = proto.Field( + proto.STRING, + number=7, + ) + recommended_deployment: str = proto.Field( + proto.STRING, + number=8, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + + +class ApiVersion(proto.Message): + r"""Describes a particular version of an API. + ApiVersions are what consumers actually use. + + Attributes: + name (str): + Resource name. + display_name (str): + Human-meaningful name. + description (str): + A detailed description. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update timestamp. + state (str): + A user-definable description of the lifecycle + phase of this API version. Format: free-form, + but we expect single words that describe API + maturity, e.g., "CONCEPT", "DESIGN", + "DEVELOPMENT", "STAGING", "PRODUCTION", + "DEPRECATED", "RETIRED". + labels (MutableMapping[str, str]): + Labels attach identifying metadata to resources. Identifying + metadata can be used to filter list operations. + + Label keys and values can be no longer than 64 characters + (Unicode codepoints), can only contain lowercase letters, + numeric characters, underscores and dashes. International + characters are allowed. No more than 64 user labels can be + associated with one resource (System labels are excluded). + + See https://goo.gl/xmQnxf for more information and examples + of labels. System reserved label keys are prefixed with + ``apigeeregistry.googleapis.com/`` and cannot be changed. + annotations (MutableMapping[str, str]): + Annotations attach non-identifying metadata + to resources. + Annotation keys and values are less restricted + than those of labels, but should be generally + used for small values of broad interest. Larger, + topic- specific metadata should be stored in + Artifacts. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + state: str = proto.Field( + proto.STRING, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + + +class ApiSpec(proto.Message): + r"""Describes a version of an API in a structured way. + ApiSpecs provide formal descriptions that consumers can use to + use a version. ApiSpec resources are intended to be + fully-resolved descriptions of an ApiVersion. When specs consist + of multiple files, these should be bundled together (e.g., in a + zip archive) and stored as a unit. Multiple specs can exist to + provide representations in different API description formats. + Synchronization of these representations would be provided by + tooling and background services. + + Attributes: + name (str): + Resource name. + filename (str): + A possibly-hierarchical name used to refer to + the spec from other specs. + description (str): + A detailed description. + revision_id (str): + Output only. Immutable. The revision ID of + the spec. A new revision is committed whenever + the spec contents are changed. The format is an + 8-character hexadecimal string. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation timestamp; when the + spec resource was created. + revision_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Revision creation timestamp; + when the represented revision was created. + revision_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update timestamp: when the + represented revision was last modified. + mime_type (str): + A style (format) descriptor for this spec that is specified + as a Media Type (https://en.wikipedia.org/wiki/Media_type). + Possible values include ``application/vnd.apigee.proto``, + ``application/vnd.apigee.openapi``, and + ``application/vnd.apigee.graphql``, with possible suffixes + representing compression types. These hypothetical names are + defined in the vendor tree defined in RFC6838 + (https://tools.ietf.org/html/rfc6838) and are not final. + Content types can specify compression. Currently only GZip + compression is supported (indicated with "+gzip"). + size_bytes (int): + Output only. The size of the spec file in + bytes. If the spec is gzipped, this is the size + of the uncompressed spec. + hash_ (str): + Output only. A SHA-256 hash of the spec's + contents. If the spec is gzipped, this is the + hash of the uncompressed spec. + source_uri (str): + The original source URI of the spec (if one + exists). This is an external location that can + be used for reference purposes but which may not + be authoritative since this external resource + may change after the spec is retrieved. + contents (bytes): + Input only. The contents of the spec. + Provided by API callers when specs are created + or updated. To access the contents of a spec, + use GetApiSpecContents. + labels (MutableMapping[str, str]): + Labels attach identifying metadata to resources. Identifying + metadata can be used to filter list operations. + + Label keys and values can be no longer than 64 characters + (Unicode codepoints), can only contain lowercase letters, + numeric characters, underscores and dashes. International + characters are allowed. No more than 64 user labels can be + associated with one resource (System labels are excluded). + + See https://goo.gl/xmQnxf for more information and examples + of labels. System reserved label keys are prefixed with + ``apigeeregistry.googleapis.com/`` and cannot be changed. + annotations (MutableMapping[str, str]): + Annotations attach non-identifying metadata + to resources. + Annotation keys and values are less restricted + than those of labels, but should be generally + used for small values of broad interest. Larger, + topic- specific metadata should be stored in + Artifacts. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + filename: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + revision_id: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + revision_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + revision_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + mime_type: str = proto.Field( + proto.STRING, + number=8, + ) + size_bytes: int = proto.Field( + proto.INT32, + number=9, + ) + hash_: str = proto.Field( + proto.STRING, + number=10, + ) + source_uri: str = proto.Field( + proto.STRING, + number=11, + ) + contents: bytes = proto.Field( + proto.BYTES, + number=12, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + + +class ApiDeployment(proto.Message): + r"""Describes a service running at particular address that + provides a particular version of an API. ApiDeployments have + revisions which correspond to different configurations of a + single deployment in time. Revision identifiers should be + updated whenever the served API spec or endpoint address + changes. + + Attributes: + name (str): + Resource name. + display_name (str): + Human-meaningful name. + description (str): + A detailed description. + revision_id (str): + Output only. Immutable. The revision ID of + the deployment. A new revision is committed + whenever the deployment contents are changed. + The format is an 8-character hexadecimal string. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation timestamp; when the + deployment resource was created. + revision_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Revision creation timestamp; + when the represented revision was created. + revision_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update timestamp: when the + represented revision was last modified. + api_spec_revision (str): + The full resource name (including revision ID) of the spec + of the API being served by the deployment. Changes to this + value will update the revision. Format: + ``apis/{api}/deployments/{deployment}`` + endpoint_uri (str): + The address where the deployment is serving. + Changes to this value will update the revision. + external_channel_uri (str): + The address of the external channel of the + API (e.g., the Developer Portal). Changes to + this value will not affect the revision. + intended_audience (str): + Text briefly identifying the intended + audience of the API. Changes to this value will + not affect the revision. + access_guidance (str): + Text briefly describing how to access the + endpoint. Changes to this value will not affect + the revision. + labels (MutableMapping[str, str]): + Labels attach identifying metadata to resources. Identifying + metadata can be used to filter list operations. + + Label keys and values can be no longer than 64 characters + (Unicode codepoints), can only contain lowercase letters, + numeric characters, underscores and dashes. International + characters are allowed. No more than 64 user labels can be + associated with one resource (System labels are excluded). + + See https://goo.gl/xmQnxf for more information and examples + of labels. System reserved label keys are prefixed with + ``apigeeregistry.googleapis.com/`` and cannot be changed. + annotations (MutableMapping[str, str]): + Annotations attach non-identifying metadata + to resources. + Annotation keys and values are less restricted + than those of labels, but should be generally + used for small values of broad interest. Larger, + topic- specific metadata should be stored in + Artifacts. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + revision_id: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + revision_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + revision_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + api_spec_revision: str = proto.Field( + proto.STRING, + number=8, + ) + endpoint_uri: str = proto.Field( + proto.STRING, + number=9, + ) + external_channel_uri: str = proto.Field( + proto.STRING, + number=10, + ) + intended_audience: str = proto.Field( + proto.STRING, + number=11, + ) + access_guidance: str = proto.Field( + proto.STRING, + number=12, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + annotations: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + + +class Artifact(proto.Message): + r"""Artifacts of resources. Artifacts are unique (single-value) per + resource and are used to store metadata that is too large or + numerous to be stored directly on the resource. Since artifacts are + stored separately from parent resources, they should generally be + used for metadata that is needed infrequently, i.e., not for display + in primary views of the resource but perhaps displayed or downloaded + upon request. The ``ListArtifacts`` method allows artifacts to be + quickly enumerated and checked for presence without downloading + their (potentially-large) contents. + + Attributes: + name (str): + Resource name. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation timestamp. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Last update timestamp. + mime_type (str): + A content type specifier for the artifact. Content type + specifiers are Media Types + (https://en.wikipedia.org/wiki/Media_type) with a possible + "schema" parameter that specifies a schema for the stored + information. Content types can specify compression. + Currently only GZip compression is supported (indicated with + "+gzip"). + size_bytes (int): + Output only. The size of the artifact in + bytes. If the artifact is gzipped, this is the + size of the uncompressed artifact. + hash_ (str): + Output only. A SHA-256 hash of the artifact's + contents. If the artifact is gzipped, this is + the hash of the uncompressed artifact. + contents (bytes): + Input only. The contents of the artifact. + Provided by API callers when artifacts are + created or replaced. To access the contents of + an artifact, use GetArtifactContents. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + mime_type: str = proto.Field( + proto.STRING, + number=4, + ) + size_bytes: int = proto.Field( + proto.INT32, + number=5, + ) + hash_: str = proto.Field( + proto.STRING, + number=6, + ) + contents: bytes = proto.Field( + proto.BYTES, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py new file mode 100644 index 0000000..ea6ea04 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py @@ -0,0 +1,1222 @@ +# -*- 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.apigee_registry_v1.types import registry_models +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.apigeeregistry.v1', + manifest={ + 'ListApisRequest', + 'ListApisResponse', + 'GetApiRequest', + 'CreateApiRequest', + 'UpdateApiRequest', + 'DeleteApiRequest', + 'ListApiVersionsRequest', + 'ListApiVersionsResponse', + 'GetApiVersionRequest', + 'CreateApiVersionRequest', + 'UpdateApiVersionRequest', + 'DeleteApiVersionRequest', + 'ListApiSpecsRequest', + 'ListApiSpecsResponse', + 'GetApiSpecRequest', + 'GetApiSpecContentsRequest', + 'CreateApiSpecRequest', + 'UpdateApiSpecRequest', + 'DeleteApiSpecRequest', + 'TagApiSpecRevisionRequest', + 'ListApiSpecRevisionsRequest', + 'ListApiSpecRevisionsResponse', + 'RollbackApiSpecRequest', + 'DeleteApiSpecRevisionRequest', + 'ListApiDeploymentsRequest', + 'ListApiDeploymentsResponse', + 'GetApiDeploymentRequest', + 'CreateApiDeploymentRequest', + 'UpdateApiDeploymentRequest', + 'DeleteApiDeploymentRequest', + 'TagApiDeploymentRevisionRequest', + 'ListApiDeploymentRevisionsRequest', + 'ListApiDeploymentRevisionsResponse', + 'RollbackApiDeploymentRequest', + 'DeleteApiDeploymentRevisionRequest', + 'ListArtifactsRequest', + 'ListArtifactsResponse', + 'GetArtifactRequest', + 'GetArtifactContentsRequest', + 'CreateArtifactRequest', + 'ReplaceArtifactRequest', + 'DeleteArtifactRequest', + }, +) + + +class ListApisRequest(proto.Message): + r"""Request message for ListApis. + + Attributes: + parent (str): + Required. The parent, which owns this collection of APIs. + Format: ``projects/*/locations/*`` + page_size (int): + The maximum number of APIs to return. + The service may return fewer than this value. If + unspecified, at most 50 values will be returned. + The maximum is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + A page token, received from a previous ``ListApis`` call. + Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListApis`` must match the call that provided the page + token. + filter (str): + An expression that can be used to filter the + list. Filters use the Common Expression Language + and can refer to all message fields. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListApisResponse(proto.Message): + r"""Response message for ListApis. + + Attributes: + apis (MutableSequence[google.cloud.apigee_registry_v1.types.Api]): + The APIs from the specified publisher. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + apis: MutableSequence[registry_models.Api] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=registry_models.Api, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetApiRequest(proto.Message): + r"""Request message for GetApi. + + Attributes: + name (str): + Required. The name of the API to retrieve. Format: + ``projects/*/locations/*/apis/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateApiRequest(proto.Message): + r"""Request message for CreateApi. + + Attributes: + parent (str): + Required. The parent, which owns this collection of APIs. + Format: ``projects/*/locations/*`` + api (google.cloud.apigee_registry_v1.types.Api): + Required. The API to create. + api_id (str): + Required. The ID to use for the API, which will become the + final component of the API's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + api: registry_models.Api = proto.Field( + proto.MESSAGE, + number=2, + message=registry_models.Api, + ) + api_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateApiRequest(proto.Message): + r"""Request message for UpdateApi. + + Attributes: + api (google.cloud.apigee_registry_v1.types.Api): + Required. The API to update. + + The ``name`` field is used to identify the API to update. + Format: ``projects/*/locations/*/apis/*`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields are + updated that are set in the request message (fields set to + default values are ignored). If an asterisk "*" is + specified, all fields are updated, including fields that are + unspecified/default in the request. + allow_missing (bool): + If set to true, and the API is not found, a new API will be + created. In this situation, ``update_mask`` is ignored. + """ + + api: registry_models.Api = proto.Field( + proto.MESSAGE, + number=1, + message=registry_models.Api, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteApiRequest(proto.Message): + r"""Request message for DeleteApi. + + Attributes: + name (str): + Required. The name of the API to delete. Format: + ``projects/*/locations/*/apis/*`` + force (bool): + If set to true, any child resources will also + be deleted. (Otherwise, the request will only + work if there are no child resources.) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListApiVersionsRequest(proto.Message): + r"""Request message for ListApiVersions. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + versions. Format: ``projects/*/locations/*/apis/*`` + page_size (int): + The maximum number of versions to return. + The service may return fewer than this value. If + unspecified, at most 50 values will be returned. + The maximum is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + A page token, received from a previous ``ListApiVersions`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListApiVersions`` must match the call that provided the + page token. + filter (str): + An expression that can be used to filter the + list. Filters use the Common Expression Language + and can refer to all message fields. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListApiVersionsResponse(proto.Message): + r"""Response message for ListApiVersions. + + Attributes: + api_versions (MutableSequence[google.cloud.apigee_registry_v1.types.ApiVersion]): + The versions from the specified publisher. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + api_versions: MutableSequence[registry_models.ApiVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=registry_models.ApiVersion, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetApiVersionRequest(proto.Message): + r"""Request message for GetApiVersion. + + Attributes: + name (str): + Required. The name of the version to retrieve. Format: + ``projects/*/locations/*/apis/*/versions/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateApiVersionRequest(proto.Message): + r"""Request message for CreateApiVersion. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + versions. Format: ``projects/*/locations/*/apis/*`` + api_version (google.cloud.apigee_registry_v1.types.ApiVersion): + Required. The version to create. + api_version_id (str): + Required. The ID to use for the version, which will become + the final component of the version's resource name. + + This value should be 1-63 characters, and valid characters + are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + api_version: registry_models.ApiVersion = proto.Field( + proto.MESSAGE, + number=2, + message=registry_models.ApiVersion, + ) + api_version_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateApiVersionRequest(proto.Message): + r"""Request message for UpdateApiVersion. + + Attributes: + api_version (google.cloud.apigee_registry_v1.types.ApiVersion): + Required. The version to update. + + The ``name`` field is used to identify the version to + update. Format: ``projects/*/locations/*/apis/*/versions/*`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields are + updated that are set in the request message (fields set to + default values are ignored). If an asterisk "*" is + specified, all fields are updated, including fields that are + unspecified/default in the request. + allow_missing (bool): + If set to true, and the version is not found, a new version + will be created. In this situation, ``update_mask`` is + ignored. + """ + + api_version: registry_models.ApiVersion = proto.Field( + proto.MESSAGE, + number=1, + message=registry_models.ApiVersion, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteApiVersionRequest(proto.Message): + r"""Request message for DeleteApiVersion. + + Attributes: + name (str): + Required. The name of the version to delete. Format: + ``projects/*/locations/*/apis/*/versions/*`` + force (bool): + If set to true, any child resources will also + be deleted. (Otherwise, the request will only + work if there are no child resources.) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class ListApiSpecsRequest(proto.Message): + r"""Request message for ListApiSpecs. + + Attributes: + parent (str): + Required. The parent, which owns this collection of specs. + Format: ``projects/*/locations/*/apis/*/versions/*`` + page_size (int): + The maximum number of specs to return. + The service may return fewer than this value. If + unspecified, at most 50 values will be returned. + The maximum is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + A page token, received from a previous ``ListApiSpecs`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListApiSpecs`` must match the call that provided the page + token. + filter (str): + An expression that can be used to filter the + list. Filters use the Common Expression Language + and can refer to all message fields except + contents. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListApiSpecsResponse(proto.Message): + r"""Response message for ListApiSpecs. + + Attributes: + api_specs (MutableSequence[google.cloud.apigee_registry_v1.types.ApiSpec]): + The specs from the specified publisher. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + api_specs: MutableSequence[registry_models.ApiSpec] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=registry_models.ApiSpec, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetApiSpecRequest(proto.Message): + r"""Request message for GetApiSpec. + + Attributes: + name (str): + Required. The name of the spec to retrieve. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetApiSpecContentsRequest(proto.Message): + r"""Request message for GetApiSpecContents. + + Attributes: + name (str): + Required. The name of the spec whose contents should be + retrieved. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateApiSpecRequest(proto.Message): + r"""Request message for CreateApiSpec. + + Attributes: + parent (str): + Required. The parent, which owns this collection of specs. + Format: ``projects/*/locations/*/apis/*/versions/*`` + api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): + Required. The spec to create. + api_spec_id (str): + Required. The ID to use for the spec, which will become the + final component of the spec's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + api_spec: registry_models.ApiSpec = proto.Field( + proto.MESSAGE, + number=2, + message=registry_models.ApiSpec, + ) + api_spec_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateApiSpecRequest(proto.Message): + r"""Request message for UpdateApiSpec. + + Attributes: + api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): + Required. The spec to update. + + The ``name`` field is used to identify the spec to update. + Format: ``projects/*/locations/*/apis/*/versions/*/specs/*`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields are + updated that are set in the request message (fields set to + default values are ignored). If an asterisk "*" is + specified, all fields are updated, including fields that are + unspecified/default in the request. + allow_missing (bool): + If set to true, and the spec is not found, a new spec will + be created. In this situation, ``update_mask`` is ignored. + """ + + api_spec: registry_models.ApiSpec = proto.Field( + proto.MESSAGE, + number=1, + message=registry_models.ApiSpec, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteApiSpecRequest(proto.Message): + r"""Request message for DeleteApiSpec. + + Attributes: + name (str): + Required. The name of the spec to delete. Format: + ``projects/*/locations/*/apis/*/versions/*/specs/*`` + force (bool): + If set to true, any child resources will also + be deleted. (Otherwise, the request will only + work if there are no child resources.) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class TagApiSpecRevisionRequest(proto.Message): + r"""Request message for TagApiSpecRevision. + + Attributes: + name (str): + Required. The name of the spec to be tagged, + including the revision ID. + tag (str): + Required. The tag to apply. The tag should be at most 40 + characters, and match ``[a-z][a-z0-9-]{3,39}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + tag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListApiSpecRevisionsRequest(proto.Message): + r"""Request message for ListApiSpecRevisions. + + Attributes: + name (str): + Required. The name of the spec to list + revisions for. + page_size (int): + The maximum number of revisions to return per + page. + page_token (str): + The page token, received from a previous + ListApiSpecRevisions call. Provide this to + retrieve the subsequent page. + """ + + name: 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, + ) + + +class ListApiSpecRevisionsResponse(proto.Message): + r"""Response message for ListApiSpecRevisionsResponse. + + Attributes: + api_specs (MutableSequence[google.cloud.apigee_registry_v1.types.ApiSpec]): + The revisions of the spec. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + api_specs: MutableSequence[registry_models.ApiSpec] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=registry_models.ApiSpec, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RollbackApiSpecRequest(proto.Message): + r"""Request message for RollbackApiSpec. + + Attributes: + name (str): + Required. The spec being rolled back. + revision_id (str): + Required. The revision ID to roll back to. It must be a + revision of the same spec. + + Example: ``c7cfa2a8`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteApiSpecRevisionRequest(proto.Message): + r"""Request message for DeleteApiSpecRevision. + + Attributes: + name (str): + Required. The name of the spec revision to be deleted, with + a revision ID explicitly included. + + Example: + ``projects/sample/locations/global/apis/petstore/versions/1.0.0/specs/openapi.yaml@c7cfa2a8`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListApiDeploymentsRequest(proto.Message): + r"""Request message for ListApiDeployments. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + deployments. Format: ``projects/*/locations/*/apis/*`` + page_size (int): + The maximum number of deployments to return. + The service may return fewer than this value. If + unspecified, at most 50 values will be returned. + The maximum is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + A page token, received from a previous + ``ListApiDeployments`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListApiDeployments`` must match the call that provided the + page token. + filter (str): + An expression that can be used to filter the + list. Filters use the Common Expression Language + and can refer to all message fields. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListApiDeploymentsResponse(proto.Message): + r"""Response message for ListApiDeployments. + + Attributes: + api_deployments (MutableSequence[google.cloud.apigee_registry_v1.types.ApiDeployment]): + The deployments from the specified publisher. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + api_deployments: MutableSequence[registry_models.ApiDeployment] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=registry_models.ApiDeployment, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetApiDeploymentRequest(proto.Message): + r"""Request message for GetApiDeployment. + + Attributes: + name (str): + Required. The name of the deployment to retrieve. Format: + ``projects/*/locations/*/apis/*/deployments/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateApiDeploymentRequest(proto.Message): + r"""Request message for CreateApiDeployment. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + deployments. Format: ``projects/*/locations/*/apis/*`` + api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): + Required. The deployment to create. + api_deployment_id (str): + Required. The ID to use for the deployment, which will + become the final component of the deployment's resource + name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + api_deployment: registry_models.ApiDeployment = proto.Field( + proto.MESSAGE, + number=2, + message=registry_models.ApiDeployment, + ) + api_deployment_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UpdateApiDeploymentRequest(proto.Message): + r"""Request message for UpdateApiDeployment. + + Attributes: + api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): + Required. The deployment to update. + + The ``name`` field is used to identify the deployment to + update. Format: + ``projects/*/locations/*/apis/*/deployments/*`` + update_mask (google.protobuf.field_mask_pb2.FieldMask): + The list of fields to be updated. If omitted, all fields are + updated that are set in the request message (fields set to + default values are ignored). If an asterisk "*" is + specified, all fields are updated, including fields that are + unspecified/default in the request. + allow_missing (bool): + If set to true, and the deployment is not found, a new + deployment will be created. In this situation, + ``update_mask`` is ignored. + """ + + api_deployment: registry_models.ApiDeployment = proto.Field( + proto.MESSAGE, + number=1, + message=registry_models.ApiDeployment, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + allow_missing: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class DeleteApiDeploymentRequest(proto.Message): + r"""Request message for DeleteApiDeployment. + + Attributes: + name (str): + Required. The name of the deployment to delete. Format: + ``projects/*/locations/*/apis/*/deployments/*`` + force (bool): + If set to true, any child resources will also + be deleted. (Otherwise, the request will only + work if there are no child resources.) + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class TagApiDeploymentRevisionRequest(proto.Message): + r"""Request message for TagApiDeploymentRevision. + + Attributes: + name (str): + Required. The name of the deployment to be + tagged, including the revision ID. + tag (str): + Required. The tag to apply. The tag should be at most 40 + characters, and match ``[a-z][a-z0-9-]{3,39}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + tag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListApiDeploymentRevisionsRequest(proto.Message): + r"""Request message for ListApiDeploymentRevisions. + + Attributes: + name (str): + Required. The name of the deployment to list + revisions for. + page_size (int): + The maximum number of revisions to return per + page. + page_token (str): + The page token, received from a previous + ListApiDeploymentRevisions call. Provide this to + retrieve the subsequent page. + """ + + name: 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, + ) + + +class ListApiDeploymentRevisionsResponse(proto.Message): + r"""Response message for ListApiDeploymentRevisionsResponse. + + Attributes: + api_deployments (MutableSequence[google.cloud.apigee_registry_v1.types.ApiDeployment]): + The revisions of the deployment. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + api_deployments: MutableSequence[registry_models.ApiDeployment] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=registry_models.ApiDeployment, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RollbackApiDeploymentRequest(proto.Message): + r"""Request message for RollbackApiDeployment. + + Attributes: + name (str): + Required. The deployment being rolled back. + revision_id (str): + Required. The revision ID to roll back to. It must be a + revision of the same deployment. + + Example: ``c7cfa2a8`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteApiDeploymentRevisionRequest(proto.Message): + r"""Request message for DeleteApiDeploymentRevision. + + Attributes: + name (str): + Required. The name of the deployment revision to be deleted, + with a revision ID explicitly included. + + Example: + ``projects/sample/locations/global/apis/petstore/deployments/prod@c7cfa2a8`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListArtifactsRequest(proto.Message): + r"""Request message for ListArtifacts. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + artifacts. Format: ``{parent}`` + page_size (int): + The maximum number of artifacts to return. + The service may return fewer than this value. If + unspecified, at most 50 values will be returned. + The maximum is 1000; values above 1000 will be + coerced to 1000. + page_token (str): + A page token, received from a previous ``ListArtifacts`` + call. Provide this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListArtifacts`` must match the call that provided the page + token. + filter (str): + An expression that can be used to filter the + list. Filters use the Common Expression Language + and can refer to all message fields except + contents. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListArtifactsResponse(proto.Message): + r"""Response message for ListArtifacts. + + Attributes: + artifacts (MutableSequence[google.cloud.apigee_registry_v1.types.Artifact]): + The artifacts from the specified publisher. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + artifacts: MutableSequence[registry_models.Artifact] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=registry_models.Artifact, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetArtifactRequest(proto.Message): + r"""Request message for GetArtifact. + + Attributes: + name (str): + Required. The name of the artifact to retrieve. Format: + ``{parent}/artifacts/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetArtifactContentsRequest(proto.Message): + r"""Request message for GetArtifactContents. + + Attributes: + name (str): + Required. The name of the artifact whose contents should be + retrieved. Format: ``{parent}/artifacts/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateArtifactRequest(proto.Message): + r"""Request message for CreateArtifact. + + Attributes: + parent (str): + Required. The parent, which owns this collection of + artifacts. Format: ``{parent}`` + artifact (google.cloud.apigee_registry_v1.types.Artifact): + Required. The artifact to create. + artifact_id (str): + Required. The ID to use for the artifact, which will become + the final component of the artifact's resource name. + + This value should be 4-63 characters, and valid characters + are /[a-z][0-9]-/. + + Following AIP-162, IDs must not have the form of a UUID. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + artifact: registry_models.Artifact = proto.Field( + proto.MESSAGE, + number=2, + message=registry_models.Artifact, + ) + artifact_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ReplaceArtifactRequest(proto.Message): + r"""Request message for ReplaceArtifact. + + Attributes: + artifact (google.cloud.apigee_registry_v1.types.Artifact): + Required. The artifact to replace. + + The ``name`` field is used to identify the artifact to + replace. Format: ``{parent}/artifacts/*`` + """ + + artifact: registry_models.Artifact = proto.Field( + proto.MESSAGE, + number=1, + message=registry_models.Artifact, + ) + + +class DeleteArtifactRequest(proto.Message): + r"""Request message for DeleteArtifact. + + Attributes: + name (str): + Required. The name of the artifact to delete. Format: + ``{parent}/artifacts/*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini new file mode 100644 index 0000000..574c5ae --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py new file mode 100644 index 0000000..6854282 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- 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. +# +import os +import pathlib +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.11" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "lint_setup_py", +] + +@nox.session(python=ALL_PYTHON) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/apigee_registry_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '--explicit-package-bases', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==4.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py new file mode 100644 index 0000000..f6d04a0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py @@ -0,0 +1,61 @@ +# -*- 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 CreateInstance +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Provisioning_CreateInstance_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 apigee_registry_v1 + + +async def sample_create_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningAsyncClient() + + # Initialize request argument(s) + instance = apigee_registry_v1.Instance() + instance.config.cmek_key_name = "cmek_key_name_value" + + request = apigee_registry_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Provisioning_CreateInstance_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py new file mode 100644 index 0000000..7d7c20a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py @@ -0,0 +1,61 @@ +# -*- 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 CreateInstance +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Provisioning_CreateInstance_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 apigee_registry_v1 + + +def sample_create_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningClient() + + # Initialize request argument(s) + instance = apigee_registry_v1.Instance() + instance.config.cmek_key_name = "cmek_key_name_value" + + request = apigee_registry_v1.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + instance=instance, + ) + + # Make the request + operation = client.create_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Provisioning_CreateInstance_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py new file mode 100644 index 0000000..a038007 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteInstance +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Provisioning_DeleteInstance_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 apigee_registry_v1 + + +async def sample_delete_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Provisioning_DeleteInstance_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py new file mode 100644 index 0000000..dca1a25 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py @@ -0,0 +1,56 @@ +# -*- 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 DeleteInstance +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Provisioning_DeleteInstance_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 apigee_registry_v1 + + +def sample_delete_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Provisioning_DeleteInstance_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_async.py new file mode 100644 index 0000000..52aaa6a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_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 GetInstance +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Provisioning_GetInstance_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 apigee_registry_v1 + + +async def sample_get_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = await client.get_instance(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Provisioning_GetInstance_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_sync.py new file mode 100644 index 0000000..cdd1e6c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_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 GetInstance +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Provisioning_GetInstance_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 apigee_registry_v1 + + +def sample_get_instance(): + # Create a client + client = apigee_registry_v1.ProvisioningClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetInstanceRequest( + name="name_value", + ) + + # Make the request + response = client.get_instance(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Provisioning_GetInstance_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py new file mode 100644 index 0000000..1a5f46c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApi_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 apigee_registry_v1 + + +async def sample_create_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiRequest( + parent="parent_value", + api_id="api_id_value", + ) + + # Make the request + response = await client.create_api(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py new file mode 100644 index 0000000..a03348a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApiDeployment_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 apigee_registry_v1 + + +async def sample_create_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiDeploymentRequest( + parent="parent_value", + api_deployment_id="api_deployment_id_value", + ) + + # Make the request + response = await client.create_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py new file mode 100644 index 0000000..7bd457b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApiDeployment_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 apigee_registry_v1 + + +def sample_create_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiDeploymentRequest( + parent="parent_value", + api_deployment_id="api_deployment_id_value", + ) + + # Make the request + response = client.create_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py new file mode 100644 index 0000000..c039d50 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApiSpec_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 apigee_registry_v1 + + +async def sample_create_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiSpecRequest( + parent="parent_value", + api_spec_id="api_spec_id_value", + ) + + # Make the request + response = await client.create_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py new file mode 100644 index 0000000..584e58d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApiSpec_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 apigee_registry_v1 + + +def sample_create_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiSpecRequest( + parent="parent_value", + api_spec_id="api_spec_id_value", + ) + + # Make the request + response = client.create_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py new file mode 100644 index 0000000..9f243bc --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApi_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 apigee_registry_v1 + + +def sample_create_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiRequest( + parent="parent_value", + api_id="api_id_value", + ) + + # Make the request + response = client.create_api(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py new file mode 100644 index 0000000..8a98de3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApiVersion_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 apigee_registry_v1 + + +async def sample_create_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiVersionRequest( + parent="parent_value", + api_version_id="api_version_id_value", + ) + + # Make the request + response = await client.create_api_version(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py new file mode 100644 index 0000000..9c848b7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateApiVersion_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 apigee_registry_v1 + + +def sample_create_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateApiVersionRequest( + parent="parent_value", + api_version_id="api_version_id_value", + ) + + # Make the request + response = client.create_api_version(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py new file mode 100644 index 0000000..508dc04 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py @@ -0,0 +1,53 @@ +# -*- 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 CreateArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateArtifact_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 apigee_registry_v1 + + +async def sample_create_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateArtifactRequest( + parent="parent_value", + artifact_id="artifact_id_value", + ) + + # Make the request + response = await client.create_artifact(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py new file mode 100644 index 0000000..296e18d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py @@ -0,0 +1,53 @@ +# -*- 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 CreateArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_CreateArtifact_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 apigee_registry_v1 + + +def sample_create_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.CreateArtifactRequest( + parent="parent_value", + artifact_id="artifact_id_value", + ) + + # Make the request + response = client.create_artifact(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_CreateArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py new file mode 100644 index 0000000..9409fc9 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApi_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 apigee_registry_v1 + + +async def sample_delete_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiRequest( + name="name_value", + ) + + # Make the request + await client.delete_api(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py new file mode 100644 index 0000000..63ccb36 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiDeployment_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 apigee_registry_v1 + + +async def sample_delete_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRequest( + name="name_value", + ) + + # Make the request + await client.delete_api_deployment(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py new file mode 100644 index 0000000..1b2c107 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_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 DeleteApiDeploymentRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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 apigee_registry_v1 + + +async def sample_delete_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_api_deployment_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py new file mode 100644 index 0000000..e7604a8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_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 DeleteApiDeploymentRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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 apigee_registry_v1 + + +def sample_delete_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_api_deployment_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py new file mode 100644 index 0000000..fc04fc0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiDeployment_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 apigee_registry_v1 + + +def sample_delete_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiDeploymentRequest( + name="name_value", + ) + + # Make the request + client.delete_api_deployment(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py new file mode 100644 index 0000000..3843e1d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiSpec_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 apigee_registry_v1 + + +async def sample_delete_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRequest( + name="name_value", + ) + + # Make the request + await client.delete_api_spec(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py new file mode 100644 index 0000000..630027f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_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 DeleteApiSpecRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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 apigee_registry_v1 + + +async def sample_delete_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_api_spec_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py new file mode 100644 index 0000000..4b80ae8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_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 DeleteApiSpecRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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 apigee_registry_v1 + + +def sample_delete_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_api_spec_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py new file mode 100644 index 0000000..4e42cdf --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiSpec_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 apigee_registry_v1 + + +def sample_delete_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiSpecRequest( + name="name_value", + ) + + # Make the request + client.delete_api_spec(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py new file mode 100644 index 0000000..69f6f7c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApi_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 apigee_registry_v1 + + +def sample_delete_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiRequest( + name="name_value", + ) + + # Make the request + client.delete_api(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py new file mode 100644 index 0000000..3365285 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiVersion_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 apigee_registry_v1 + + +async def sample_delete_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_api_version(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py new file mode 100644 index 0000000..de4d888 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteApiVersion_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 apigee_registry_v1 + + +def sample_delete_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteApiVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_api_version(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py new file mode 100644 index 0000000..969bac2 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteArtifact_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 apigee_registry_v1 + + +async def sample_delete_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteArtifactRequest( + name="name_value", + ) + + # Make the request + await client.delete_artifact(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py new file mode 100644 index 0000000..69a30e8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py @@ -0,0 +1,50 @@ +# -*- 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 DeleteArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_DeleteArtifact_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 apigee_registry_v1 + + +def sample_delete_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.DeleteArtifactRequest( + name="name_value", + ) + + # Make the request + client.delete_artifact(request=request) + + +# [END apigeeregistry_v1_generated_Registry_DeleteArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_async.py new file mode 100644 index 0000000..a540000 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_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 GetApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApi_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 apigee_registry_v1 + + +async def sample_get_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_async.py new file mode 100644 index 0000000..86643b1 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_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 GetApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiDeployment_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 apigee_registry_v1 + + +async def sample_get_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_sync.py new file mode 100644 index 0000000..35577ae --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_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 GetApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiDeployment_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 apigee_registry_v1 + + +def sample_get_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_async.py new file mode 100644 index 0000000..07e3d84 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_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 GetApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiSpec_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 apigee_registry_v1 + + +async def sample_get_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py new file mode 100644 index 0000000..ef4f3e4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_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 GetApiSpecContents +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiSpecContents_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 apigee_registry_v1 + + +async def sample_get_api_spec_contents(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecContentsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_spec_contents(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiSpecContents_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py new file mode 100644 index 0000000..da917ef --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_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 GetApiSpecContents +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiSpecContents_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 apigee_registry_v1 + + +def sample_get_api_spec_contents(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecContentsRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_spec_contents(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiSpecContents_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_sync.py new file mode 100644 index 0000000..0cb8879 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_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 GetApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiSpec_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 apigee_registry_v1 + + +def sample_get_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiSpecRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_sync.py new file mode 100644 index 0000000..8257a52 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_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 GetApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApi_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 apigee_registry_v1 + + +def sample_get_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiRequest( + name="name_value", + ) + + # Make the request + response = client.get_api(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_async.py new file mode 100644 index 0000000..2452e5e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_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 GetApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiVersion_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 apigee_registry_v1 + + +async def sample_get_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_api_version(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_sync.py new file mode 100644 index 0000000..780eba2 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_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 GetApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetApiVersion_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 apigee_registry_v1 + + +def sample_get_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetApiVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_api_version(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_async.py new file mode 100644 index 0000000..c8c7f51 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_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 GetArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetArtifact_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 apigee_registry_v1 + + +async def sample_get_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactRequest( + name="name_value", + ) + + # Make the request + response = await client.get_artifact(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_async.py new file mode 100644 index 0000000..c0a612e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_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 GetArtifactContents +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetArtifactContents_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 apigee_registry_v1 + + +async def sample_get_artifact_contents(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactContentsRequest( + name="name_value", + ) + + # Make the request + response = await client.get_artifact_contents(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetArtifactContents_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py new file mode 100644 index 0000000..1f76c6b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_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 GetArtifactContents +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetArtifactContents_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 apigee_registry_v1 + + +def sample_get_artifact_contents(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactContentsRequest( + name="name_value", + ) + + # Make the request + response = client.get_artifact_contents(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetArtifactContents_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_sync.py new file mode 100644 index 0000000..5715ea5 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_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 GetArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_GetArtifact_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 apigee_registry_v1 + + +def sample_get_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.GetArtifactRequest( + name="name_value", + ) + + # Make the request + response = client.get_artifact(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_GetArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py new file mode 100644 index 0000000..3ae35f4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiDeploymentRevisions +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_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 apigee_registry_v1 + + +async def sample_list_api_deployment_revisions(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_deployment_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py new file mode 100644 index 0000000..0287d20 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiDeploymentRevisions +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_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 apigee_registry_v1 + + +def sample_list_api_deployment_revisions(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_deployment_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py new file mode 100644 index 0000000..30a018c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiDeployments +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiDeployments_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 apigee_registry_v1 + + +async def sample_list_api_deployments(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiDeployments_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py new file mode 100644 index 0000000..e3ea45d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiDeployments +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiDeployments_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 apigee_registry_v1 + + +def sample_list_api_deployments(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiDeployments_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py new file mode 100644 index 0000000..addf14b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiSpecRevisions +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_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 apigee_registry_v1 + + +async def sample_list_api_spec_revisions(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_spec_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py new file mode 100644 index 0000000..aca22d7 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiSpecRevisions +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_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 apigee_registry_v1 + + +def sample_list_api_spec_revisions(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_api_spec_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py new file mode 100644 index 0000000..d6dc72b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiSpecs +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiSpecs_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 apigee_registry_v1 + + +async def sample_list_api_specs(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_specs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiSpecs_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py new file mode 100644 index 0000000..c1d948e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiSpecs +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiSpecs_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 apigee_registry_v1 + + +def sample_list_api_specs(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiSpecsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_specs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiSpecs_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py new file mode 100644 index 0000000..0ba03f3 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiVersions +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiVersions_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 apigee_registry_v1 + + +async def sample_list_api_versions(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiVersions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py new file mode 100644 index 0000000..915b612 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListApiVersions +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApiVersions_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 apigee_registry_v1 + + +def sample_list_api_versions(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApiVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_api_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApiVersions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py new file mode 100644 index 0000000..2952b92 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListApis +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApis_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 apigee_registry_v1 + + +async def sample_list_apis(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApisRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apis(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApis_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py new file mode 100644 index 0000000..4d8502c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListApis +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListApis_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 apigee_registry_v1 + + +def sample_list_apis(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListApisRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apis(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListApis_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py new file mode 100644 index 0000000..798682c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py @@ -0,0 +1,53 @@ +# -*- 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 ListArtifacts +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListArtifacts_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 apigee_registry_v1 + + +async def sample_list_artifacts(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListArtifactsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_artifacts(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListArtifacts_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py new file mode 100644 index 0000000..ba38cd1 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py @@ -0,0 +1,53 @@ +# -*- 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 ListArtifacts +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ListArtifacts_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 apigee_registry_v1 + + +def sample_list_artifacts(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ListArtifactsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_artifacts(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END apigeeregistry_v1_generated_Registry_ListArtifacts_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py new file mode 100644 index 0000000..068f245 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py @@ -0,0 +1,51 @@ +# -*- 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 ReplaceArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ReplaceArtifact_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 apigee_registry_v1 + + +async def sample_replace_artifact(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ReplaceArtifactRequest( + ) + + # Make the request + response = await client.replace_artifact(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_ReplaceArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py new file mode 100644 index 0000000..3a1210b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py @@ -0,0 +1,51 @@ +# -*- 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 ReplaceArtifact +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_ReplaceArtifact_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 apigee_registry_v1 + + +def sample_replace_artifact(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.ReplaceArtifactRequest( + ) + + # Make the request + response = client.replace_artifact(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_ReplaceArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py new file mode 100644 index 0000000..a8b26ca --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py @@ -0,0 +1,53 @@ +# -*- 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 RollbackApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_RollbackApiDeployment_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 apigee_registry_v1 + + +async def sample_rollback_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiDeploymentRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = await client.rollback_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_RollbackApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py new file mode 100644 index 0000000..510524b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py @@ -0,0 +1,53 @@ +# -*- 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 RollbackApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_RollbackApiDeployment_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 apigee_registry_v1 + + +def sample_rollback_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiDeploymentRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = client.rollback_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_RollbackApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py new file mode 100644 index 0000000..db76ddc --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py @@ -0,0 +1,53 @@ +# -*- 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 RollbackApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_RollbackApiSpec_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 apigee_registry_v1 + + +async def sample_rollback_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiSpecRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = await client.rollback_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_RollbackApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py new file mode 100644 index 0000000..836f10b --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py @@ -0,0 +1,53 @@ +# -*- 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 RollbackApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_RollbackApiSpec_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 apigee_registry_v1 + + +def sample_rollback_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.RollbackApiSpecRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = client.rollback_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_RollbackApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py new file mode 100644 index 0000000..7ac740a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py @@ -0,0 +1,53 @@ +# -*- 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 TagApiDeploymentRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_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 apigee_registry_v1 + + +async def sample_tag_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiDeploymentRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = await client.tag_api_deployment_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py new file mode 100644 index 0000000..315be45 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py @@ -0,0 +1,53 @@ +# -*- 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 TagApiDeploymentRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_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 apigee_registry_v1 + + +def sample_tag_api_deployment_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiDeploymentRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = client.tag_api_deployment_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py new file mode 100644 index 0000000..b97e8a6 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py @@ -0,0 +1,53 @@ +# -*- 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 TagApiSpecRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_TagApiSpecRevision_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 apigee_registry_v1 + + +async def sample_tag_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiSpecRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = await client.tag_api_spec_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_TagApiSpecRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py new file mode 100644 index 0000000..d5ddbfb --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py @@ -0,0 +1,53 @@ +# -*- 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 TagApiSpecRevision +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_TagApiSpecRevision_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 apigee_registry_v1 + + +def sample_tag_api_spec_revision(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.TagApiSpecRevisionRequest( + name="name_value", + tag="tag_value", + ) + + # Make the request + response = client.tag_api_spec_revision(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_TagApiSpecRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py new file mode 100644 index 0000000..7f0185c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApi_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 apigee_registry_v1 + + +async def sample_update_api(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiRequest( + ) + + # Make the request + response = await client.update_api(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py new file mode 100644 index 0000000..34fd971 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApiDeployment_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 apigee_registry_v1 + + +async def sample_update_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiDeploymentRequest( + ) + + # Make the request + response = await client.update_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py new file mode 100644 index 0000000..144d745 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApiDeployment +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApiDeployment_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 apigee_registry_v1 + + +def sample_update_api_deployment(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiDeploymentRequest( + ) + + # Make the request + response = client.update_api_deployment(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py new file mode 100644 index 0000000..03059fa --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApiSpec_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 apigee_registry_v1 + + +async def sample_update_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiSpecRequest( + ) + + # Make the request + response = await client.update_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py new file mode 100644 index 0000000..013de05 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApiSpec +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApiSpec_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 apigee_registry_v1 + + +def sample_update_api_spec(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiSpecRequest( + ) + + # Make the request + response = client.update_api_spec(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py new file mode 100644 index 0000000..1991426 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApi +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApi_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 apigee_registry_v1 + + +def sample_update_api(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiRequest( + ) + + # Make the request + response = client.update_api(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py new file mode 100644 index 0000000..e275a66 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApiVersion_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 apigee_registry_v1 + + +async def sample_update_api_version(): + # Create a client + client = apigee_registry_v1.RegistryAsyncClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiVersionRequest( + ) + + # Make the request + response = await client.update_api_version(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py new file mode 100644 index 0000000..af01cc8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py @@ -0,0 +1,51 @@ +# -*- 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 UpdateApiVersion +# 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-apigee-registry + + +# [START apigeeregistry_v1_generated_Registry_UpdateApiVersion_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 apigee_registry_v1 + + +def sample_update_api_version(): + # Create a client + client = apigee_registry_v1.RegistryClient() + + # Initialize request argument(s) + request = apigee_registry_v1.UpdateApiVersionRequest( + ) + + # Make the request + response = client.update_api_version(request=request) + + # Handle the response + print(response) + +# [END apigeeregistry_v1_generated_Registry_UpdateApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json new file mode 100644 index 0000000..399743e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json @@ -0,0 +1,6183 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.apigeeregistry.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-apigee-registry", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient", + "shortName": "ProvisioningAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient.create_instance", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning.CreateInstance", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning", + "shortName": "Provisioning" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.apigee_registry_v1.types.Instance" + }, + { + "name": "instance_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "apigeeregistry_v1_generated_provisioning_create_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Provisioning_CreateInstance_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_provisioning_create_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient", + "shortName": "ProvisioningClient" + }, + "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient.create_instance", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning.CreateInstance", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning", + "shortName": "Provisioning" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.apigee_registry_v1.types.Instance" + }, + { + "name": "instance_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "apigeeregistry_v1_generated_provisioning_create_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Provisioning_CreateInstance_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_provisioning_create_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient", + "shortName": "ProvisioningAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning.DeleteInstance", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning", + "shortName": "Provisioning" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "apigeeregistry_v1_generated_provisioning_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Provisioning_DeleteInstance_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_provisioning_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient", + "shortName": "ProvisioningClient" + }, + "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient.delete_instance", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning.DeleteInstance", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning", + "shortName": "Provisioning" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "apigeeregistry_v1_generated_provisioning_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Provisioning_DeleteInstance_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_provisioning_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient", + "shortName": "ProvisioningAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning.GetInstance", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning", + "shortName": "Provisioning" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetInstanceRequest" + }, + { + "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.apigee_registry_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "apigeeregistry_v1_generated_provisioning_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Provisioning_GetInstance_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": "apigeeregistry_v1_generated_provisioning_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient", + "shortName": "ProvisioningClient" + }, + "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient.get_instance", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning.GetInstance", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Provisioning", + "shortName": "Provisioning" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetInstanceRequest" + }, + { + "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.apigee_registry_v1.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "apigeeregistry_v1_generated_provisioning_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Provisioning_GetInstance_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": "apigeeregistry_v1_generated_provisioning_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api_deployment", + "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" + }, + { + "name": "api_deployment_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "create_api_deployment" + }, + "description": "Sample for CreateApiDeployment", + "file": "apigeeregistry_v1_generated_registry_create_api_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiDeployment_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api_deployment", + "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" + }, + { + "name": "api_deployment_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "create_api_deployment" + }, + "description": "Sample for CreateApiDeployment", + "file": "apigeeregistry_v1_generated_registry_create_api_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiDeployment_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiSpecRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api_spec", + "type": "google.cloud.apigee_registry_v1.types.ApiSpec" + }, + { + "name": "api_spec_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "create_api_spec" + }, + "description": "Sample for CreateApiSpec", + "file": "apigeeregistry_v1_generated_registry_create_api_spec_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiSpec_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_spec_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiSpecRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api_spec", + "type": "google.cloud.apigee_registry_v1.types.ApiSpec" + }, + { + "name": "api_spec_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "create_api_spec" + }, + "description": "Sample for CreateApiSpec", + "file": "apigeeregistry_v1_generated_registry_create_api_spec_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiSpec_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_spec_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api_version", + "type": "google.cloud.apigee_registry_v1.types.ApiVersion" + }, + { + "name": "api_version_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", + "shortName": "create_api_version" + }, + "description": "Sample for CreateApiVersion", + "file": "apigeeregistry_v1_generated_registry_create_api_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiVersion_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api_version", + "type": "google.cloud.apigee_registry_v1.types.ApiVersion" + }, + { + "name": "api_version_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", + "shortName": "create_api_version" + }, + "description": "Sample for CreateApiVersion", + "file": "apigeeregistry_v1_generated_registry_create_api_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiVersion_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api", + "type": "google.cloud.apigee_registry_v1.types.Api" + }, + { + "name": "api_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Api", + "shortName": "create_api" + }, + "description": "Sample for CreateApi", + "file": "apigeeregistry_v1_generated_registry_create_api_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApi_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateApiRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "api", + "type": "google.cloud.apigee_registry_v1.types.Api" + }, + { + "name": "api_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Api", + "shortName": "create_api" + }, + "description": "Sample for CreateApi", + "file": "apigeeregistry_v1_generated_registry_create_api_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateApi_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_api_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateArtifactRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "artifact", + "type": "google.cloud.apigee_registry_v1.types.Artifact" + }, + { + "name": "artifact_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Artifact", + "shortName": "create_artifact" + }, + "description": "Sample for CreateArtifact", + "file": "apigeeregistry_v1_generated_registry_create_artifact_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateArtifact_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_artifact_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "CreateArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.CreateArtifactRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "artifact", + "type": "google.cloud.apigee_registry_v1.types.Artifact" + }, + { + "name": "artifact_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Artifact", + "shortName": "create_artifact" + }, + "description": "Sample for CreateArtifact", + "file": "apigeeregistry_v1_generated_registry_create_artifact_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_CreateArtifact_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_create_artifact_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_deployment_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeploymentRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiDeploymentRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest" + }, + { + "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.apigee_registry_v1.types.ApiDeployment", + "shortName": "delete_api_deployment_revision" + }, + "description": "Sample for DeleteApiDeploymentRevision", + "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_deployment_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeploymentRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiDeploymentRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest" + }, + { + "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.apigee_registry_v1.types.ApiDeployment", + "shortName": "delete_api_deployment_revision" + }, + "description": "Sample for DeleteApiDeploymentRevision", + "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api_deployment" + }, + "description": "Sample for DeleteApiDeployment", + "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeployment_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api_deployment" + }, + "description": "Sample for DeleteApiDeployment", + "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeployment_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_spec_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpecRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiSpecRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest" + }, + { + "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.apigee_registry_v1.types.ApiSpec", + "shortName": "delete_api_spec_revision" + }, + "description": "Sample for DeleteApiSpecRevision", + "file": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_spec_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpecRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiSpecRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest" + }, + { + "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.apigee_registry_v1.types.ApiSpec", + "shortName": "delete_api_spec_revision" + }, + "description": "Sample for DeleteApiSpecRevision", + "file": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api_spec" + }, + "description": "Sample for DeleteApiSpec", + "file": "apigeeregistry_v1_generated_registry_delete_api_spec_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpec_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_spec_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api_spec" + }, + "description": "Sample for DeleteApiSpec", + "file": "apigeeregistry_v1_generated_registry_delete_api_spec_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpec_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_spec_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api_version" + }, + "description": "Sample for DeleteApiVersion", + "file": "apigeeregistry_v1_generated_registry_delete_api_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiVersion_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api_version" + }, + "description": "Sample for DeleteApiVersion", + "file": "apigeeregistry_v1_generated_registry_delete_api_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiVersion_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api" + }, + "description": "Sample for DeleteApi", + "file": "apigeeregistry_v1_generated_registry_delete_api_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApi_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteApiRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_api" + }, + "description": "Sample for DeleteApi", + "file": "apigeeregistry_v1_generated_registry_delete_api_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApi_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_api_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteArtifactRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_artifact" + }, + "description": "Sample for DeleteArtifact", + "file": "apigeeregistry_v1_generated_registry_delete_artifact_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteArtifact_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_artifact_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "DeleteArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.DeleteArtifactRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "shortName": "delete_artifact" + }, + "description": "Sample for DeleteArtifact", + "file": "apigeeregistry_v1_generated_registry_delete_artifact_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_DeleteArtifact_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_delete_artifact_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest" + }, + { + "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.apigee_registry_v1.types.ApiDeployment", + "shortName": "get_api_deployment" + }, + "description": "Sample for GetApiDeployment", + "file": "apigeeregistry_v1_generated_registry_get_api_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiDeployment_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": "apigeeregistry_v1_generated_registry_get_api_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest" + }, + { + "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.apigee_registry_v1.types.ApiDeployment", + "shortName": "get_api_deployment" + }, + "description": "Sample for GetApiDeployment", + "file": "apigeeregistry_v1_generated_registry_get_api_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiDeployment_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": "apigeeregistry_v1_generated_registry_get_api_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_spec_contents", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpecContents", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiSpecContents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "get_api_spec_contents" + }, + "description": "Sample for GetApiSpecContents", + "file": "apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpecContents_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": "apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_spec_contents", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpecContents", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiSpecContents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "get_api_spec_contents" + }, + "description": "Sample for GetApiSpecContents", + "file": "apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpecContents_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": "apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiSpecRequest" + }, + { + "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.apigee_registry_v1.types.ApiSpec", + "shortName": "get_api_spec" + }, + "description": "Sample for GetApiSpec", + "file": "apigeeregistry_v1_generated_registry_get_api_spec_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpec_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": "apigeeregistry_v1_generated_registry_get_api_spec_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiSpecRequest" + }, + { + "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.apigee_registry_v1.types.ApiSpec", + "shortName": "get_api_spec" + }, + "description": "Sample for GetApiSpec", + "file": "apigeeregistry_v1_generated_registry_get_api_spec_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpec_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": "apigeeregistry_v1_generated_registry_get_api_spec_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiVersionRequest" + }, + { + "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.apigee_registry_v1.types.ApiVersion", + "shortName": "get_api_version" + }, + "description": "Sample for GetApiVersion", + "file": "apigeeregistry_v1_generated_registry_get_api_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiVersion_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": "apigeeregistry_v1_generated_registry_get_api_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiVersionRequest" + }, + { + "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.apigee_registry_v1.types.ApiVersion", + "shortName": "get_api_version" + }, + "description": "Sample for GetApiVersion", + "file": "apigeeregistry_v1_generated_registry_get_api_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApiVersion_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": "apigeeregistry_v1_generated_registry_get_api_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiRequest" + }, + { + "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.apigee_registry_v1.types.Api", + "shortName": "get_api" + }, + "description": "Sample for GetApi", + "file": "apigeeregistry_v1_generated_registry_get_api_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApi_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": "apigeeregistry_v1_generated_registry_get_api_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetApiRequest" + }, + { + "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.apigee_registry_v1.types.Api", + "shortName": "get_api" + }, + "description": "Sample for GetApi", + "file": "apigeeregistry_v1_generated_registry_get_api_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetApi_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": "apigeeregistry_v1_generated_registry_get_api_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_artifact_contents", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifactContents", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetArtifactContents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "get_artifact_contents" + }, + "description": "Sample for GetArtifactContents", + "file": "apigeeregistry_v1_generated_registry_get_artifact_contents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifactContents_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": "apigeeregistry_v1_generated_registry_get_artifact_contents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_artifact_contents", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifactContents", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetArtifactContents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api.httpbody_pb2.HttpBody", + "shortName": "get_artifact_contents" + }, + "description": "Sample for GetArtifactContents", + "file": "apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifactContents_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": "apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetArtifactRequest" + }, + { + "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.apigee_registry_v1.types.Artifact", + "shortName": "get_artifact" + }, + "description": "Sample for GetArtifact", + "file": "apigeeregistry_v1_generated_registry_get_artifact_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifact_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": "apigeeregistry_v1_generated_registry_get_artifact_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "GetArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.GetArtifactRequest" + }, + { + "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.apigee_registry_v1.types.Artifact", + "shortName": "get_artifact" + }, + "description": "Sample for GetArtifact", + "file": "apigeeregistry_v1_generated_registry_get_artifact_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifact_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": "apigeeregistry_v1_generated_registry_get_artifact_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_deployment_revisions", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeploymentRevisions", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiDeploymentRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsAsyncPager", + "shortName": "list_api_deployment_revisions" + }, + "description": "Sample for ListApiDeploymentRevisions", + "file": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_deployment_revisions", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeploymentRevisions", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiDeploymentRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsPager", + "shortName": "list_api_deployment_revisions" + }, + "description": "Sample for ListApiDeploymentRevisions", + "file": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_deployments", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeployments", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsAsyncPager", + "shortName": "list_api_deployments" + }, + "description": "Sample for ListApiDeployments", + "file": "apigeeregistry_v1_generated_registry_list_api_deployments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeployments_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_deployments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_deployments", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeployments", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsPager", + "shortName": "list_api_deployments" + }, + "description": "Sample for ListApiDeployments", + "file": "apigeeregistry_v1_generated_registry_list_api_deployments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeployments_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_deployments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_spec_revisions", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecRevisions", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiSpecRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsAsyncPager", + "shortName": "list_api_spec_revisions" + }, + "description": "Sample for ListApiSpecRevisions", + "file": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_spec_revisions", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecRevisions", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiSpecRevisions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsPager", + "shortName": "list_api_spec_revisions" + }, + "description": "Sample for ListApiSpecRevisions", + "file": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_specs", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecs", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiSpecs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiSpecsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApiSpecsAsyncPager", + "shortName": "list_api_specs" + }, + "description": "Sample for ListApiSpecs", + "file": "apigeeregistry_v1_generated_registry_list_api_specs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_specs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_specs", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecs", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiSpecs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiSpecsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApiSpecsPager", + "shortName": "list_api_specs" + }, + "description": "Sample for ListApiSpecs", + "file": "apigeeregistry_v1_generated_registry_list_api_specs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_specs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_versions", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiVersions", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiVersionsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApiVersionsAsyncPager", + "shortName": "list_api_versions" + }, + "description": "Sample for ListApiVersions", + "file": "apigeeregistry_v1_generated_registry_list_api_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiVersions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_versions", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiVersions", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApiVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApiVersionsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApiVersionsPager", + "shortName": "list_api_versions" + }, + "description": "Sample for ListApiVersions", + "file": "apigeeregistry_v1_generated_registry_list_api_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApiVersions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_api_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_apis", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApis", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApisRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApisAsyncPager", + "shortName": "list_apis" + }, + "description": "Sample for ListApis", + "file": "apigeeregistry_v1_generated_registry_list_apis_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApis_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_apis_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_apis", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApis", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListApis" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListApisRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListApisPager", + "shortName": "list_apis" + }, + "description": "Sample for ListApis", + "file": "apigeeregistry_v1_generated_registry_list_apis_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListApis_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_apis_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_artifacts", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListArtifacts", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListArtifacts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListArtifactsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListArtifactsAsyncPager", + "shortName": "list_artifacts" + }, + "description": "Sample for ListArtifacts", + "file": "apigeeregistry_v1_generated_registry_list_artifacts_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListArtifacts_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_artifacts_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_artifacts", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ListArtifacts", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ListArtifacts" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ListArtifactsRequest" + }, + { + "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.apigee_registry_v1.services.registry.pagers.ListArtifactsPager", + "shortName": "list_artifacts" + }, + "description": "Sample for ListArtifacts", + "file": "apigeeregistry_v1_generated_registry_list_artifacts_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ListArtifacts_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_list_artifacts_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.replace_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ReplaceArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ReplaceArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest" + }, + { + "name": "artifact", + "type": "google.cloud.apigee_registry_v1.types.Artifact" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Artifact", + "shortName": "replace_artifact" + }, + "description": "Sample for ReplaceArtifact", + "file": "apigeeregistry_v1_generated_registry_replace_artifact_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ReplaceArtifact_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_replace_artifact_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.replace_artifact", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.ReplaceArtifact", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "ReplaceArtifact" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest" + }, + { + "name": "artifact", + "type": "google.cloud.apigee_registry_v1.types.Artifact" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Artifact", + "shortName": "replace_artifact" + }, + "description": "Sample for ReplaceArtifact", + "file": "apigeeregistry_v1_generated_registry_replace_artifact_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_ReplaceArtifact_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_replace_artifact_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.rollback_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "RollbackApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "rollback_api_deployment" + }, + "description": "Sample for RollbackApiDeployment", + "file": "apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiDeployment_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.rollback_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "RollbackApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "rollback_api_deployment" + }, + "description": "Sample for RollbackApiDeployment", + "file": "apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiDeployment_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.rollback_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "RollbackApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "rollback_api_spec" + }, + "description": "Sample for RollbackApiSpec", + "file": "apigeeregistry_v1_generated_registry_rollback_api_spec_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiSpec_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_rollback_api_spec_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.rollback_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "RollbackApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "rollback_api_spec" + }, + "description": "Sample for RollbackApiSpec", + "file": "apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiSpec_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.tag_api_deployment_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiDeploymentRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "TagApiDeploymentRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "tag_api_deployment_revision" + }, + "description": "Sample for TagApiDeploymentRevision", + "file": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.tag_api_deployment_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiDeploymentRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "TagApiDeploymentRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "tag_api_deployment_revision" + }, + "description": "Sample for TagApiDeploymentRevision", + "file": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.tag_api_spec_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiSpecRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "TagApiSpecRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "tag_api_spec_revision" + }, + "description": "Sample for TagApiSpecRevision", + "file": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_TagApiSpecRevision_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.tag_api_spec_revision", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiSpecRevision", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "TagApiSpecRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "tag_api_spec_revision" + }, + "description": "Sample for TagApiSpecRevision", + "file": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_TagApiSpecRevision_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest" + }, + { + "name": "api_deployment", + "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "update_api_deployment" + }, + "description": "Sample for UpdateApiDeployment", + "file": "apigeeregistry_v1_generated_registry_update_api_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiDeployment_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api_deployment", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiDeployment", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApiDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest" + }, + { + "name": "api_deployment", + "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", + "shortName": "update_api_deployment" + }, + "description": "Sample for UpdateApiDeployment", + "file": "apigeeregistry_v1_generated_registry_update_api_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiDeployment_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest" + }, + { + "name": "api_spec", + "type": "google.cloud.apigee_registry_v1.types.ApiSpec" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "update_api_spec" + }, + "description": "Sample for UpdateApiSpec", + "file": "apigeeregistry_v1_generated_registry_update_api_spec_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiSpec_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_spec_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api_spec", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiSpec", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApiSpec" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest" + }, + { + "name": "api_spec", + "type": "google.cloud.apigee_registry_v1.types.ApiSpec" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", + "shortName": "update_api_spec" + }, + "description": "Sample for UpdateApiSpec", + "file": "apigeeregistry_v1_generated_registry_update_api_spec_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiSpec_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_spec_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest" + }, + { + "name": "api_version", + "type": "google.cloud.apigee_registry_v1.types.ApiVersion" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", + "shortName": "update_api_version" + }, + "description": "Sample for UpdateApiVersion", + "file": "apigeeregistry_v1_generated_registry_update_api_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiVersion_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api_version", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiVersion", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApiVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest" + }, + { + "name": "api_version", + "type": "google.cloud.apigee_registry_v1.types.ApiVersion" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", + "shortName": "update_api_version" + }, + "description": "Sample for UpdateApiVersion", + "file": "apigeeregistry_v1_generated_registry_update_api_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiVersion_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", + "shortName": "RegistryAsyncClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiRequest" + }, + { + "name": "api", + "type": "google.cloud.apigee_registry_v1.types.Api" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Api", + "shortName": "update_api" + }, + "description": "Sample for UpdateApi", + "file": "apigeeregistry_v1_generated_registry_update_api_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApi_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.apigee_registry_v1.RegistryClient", + "shortName": "RegistryClient" + }, + "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api", + "method": { + "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApi", + "service": { + "fullName": "google.cloud.apigeeregistry.v1.Registry", + "shortName": "Registry" + }, + "shortName": "UpdateApi" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.apigee_registry_v1.types.UpdateApiRequest" + }, + { + "name": "api", + "type": "google.cloud.apigee_registry_v1.types.Api" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.apigee_registry_v1.types.Api", + "shortName": "update_api" + }, + "description": "Sample for UpdateApi", + "file": "apigeeregistry_v1_generated_registry_update_api_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApi_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "apigeeregistry_v1_generated_registry_update_api_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py new file mode 100644 index 0000000..e82af4a --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py @@ -0,0 +1,213 @@ +#! /usr/bin/env python3 +# -*- 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. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class apigee_registryCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_api': ('parent', 'api', 'api_id', ), + 'create_api_deployment': ('parent', 'api_deployment', 'api_deployment_id', ), + 'create_api_spec': ('parent', 'api_spec', 'api_spec_id', ), + 'create_api_version': ('parent', 'api_version', 'api_version_id', ), + 'create_artifact': ('parent', 'artifact', 'artifact_id', ), + 'create_instance': ('parent', 'instance_id', 'instance', ), + 'delete_api': ('name', 'force', ), + 'delete_api_deployment': ('name', 'force', ), + 'delete_api_deployment_revision': ('name', ), + 'delete_api_spec': ('name', 'force', ), + 'delete_api_spec_revision': ('name', ), + 'delete_api_version': ('name', 'force', ), + 'delete_artifact': ('name', ), + 'delete_instance': ('name', ), + 'get_api': ('name', ), + 'get_api_deployment': ('name', ), + 'get_api_spec': ('name', ), + 'get_api_spec_contents': ('name', ), + 'get_api_version': ('name', ), + 'get_artifact': ('name', ), + 'get_artifact_contents': ('name', ), + 'get_instance': ('name', ), + 'list_api_deployment_revisions': ('name', 'page_size', 'page_token', ), + 'list_api_deployments': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_apis': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_api_spec_revisions': ('name', 'page_size', 'page_token', ), + 'list_api_specs': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_api_versions': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_artifacts': ('parent', 'page_size', 'page_token', 'filter', ), + 'replace_artifact': ('artifact', ), + 'rollback_api_deployment': ('name', 'revision_id', ), + 'rollback_api_spec': ('name', 'revision_id', ), + 'tag_api_deployment_revision': ('name', 'tag', ), + 'tag_api_spec_revision': ('name', 'tag', ), + 'update_api': ('api', 'update_mask', 'allow_missing', ), + 'update_api_deployment': ('api_deployment', 'update_mask', 'allow_missing', ), + 'update_api_spec': ('api_spec', 'update_mask', 'allow_missing', ), + 'update_api_version': ('api_version', 'update_mask', 'allow_missing', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=apigee_registryCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the apigee_registry client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py new file mode 100644 index 0000000..01aa9ca --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,91 @@ +# -*- 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. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-apigee-registry' + + +description = "Google Cloud Apigee Registry API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/apigee_registry/gapic_version.py')) as fp: + exec(fp.read(), version) +version = version["__version__"] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +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', +] +url = "https://github.com/googleapis/python-apigee-registry" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google", "google.cloud"] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.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", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.10.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 diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.11.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 diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/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 diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt new file mode 100644 index 0000000..2beecf9 --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +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/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.8.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 diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/owl-bot-staging/v1/testing/constraints-3.9.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 diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py new file mode 100644 index 0000000..231bc12 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py new file mode 100644 index 0000000..d5039bd --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py @@ -0,0 +1,4396 @@ +# -*- 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. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.apigee_registry_v1.services.provisioning import ProvisioningAsyncClient +from google.cloud.apigee_registry_v1.services.provisioning import ProvisioningClient +from google.cloud.apigee_registry_v1.services.provisioning import transports +from google.cloud.apigee_registry_v1.types import provisioning_service +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 empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProvisioningClient._get_default_mtls_endpoint(None) is None + assert ProvisioningClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ProvisioningClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert ProvisioningClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert ProvisioningClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert ProvisioningClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProvisioningClient, "grpc"), + (ProvisioningAsyncClient, "grpc_asyncio"), + (ProvisioningClient, "rest"), +]) +def test_provisioning_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://apigeeregistry.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.ProvisioningGrpcTransport, "grpc"), + (transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ProvisioningRestTransport, "rest"), +]) +def test_provisioning_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (ProvisioningClient, "grpc"), + (ProvisioningAsyncClient, "grpc_asyncio"), + (ProvisioningClient, "rest"), +]) +def test_provisioning_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://apigeeregistry.googleapis.com' + ) + + +def test_provisioning_client_get_transport_class(): + transport = ProvisioningClient.get_transport_class() + available_transports = [ + transports.ProvisioningGrpcTransport, + transports.ProvisioningRestTransport, + ] + assert transport in available_transports + + transport = ProvisioningClient.get_transport_class("grpc") + assert transport == transports.ProvisioningGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc"), + (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio"), + (ProvisioningClient, transports.ProvisioningRestTransport, "rest"), +]) +@mock.patch.object(ProvisioningClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningClient)) +@mock.patch.object(ProvisioningAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningAsyncClient)) +def test_provisioning_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ProvisioningClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ProvisioningClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", "true"), + (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", "false"), + (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (ProvisioningClient, transports.ProvisioningRestTransport, "rest", "true"), + (ProvisioningClient, transports.ProvisioningRestTransport, "rest", "false"), +]) +@mock.patch.object(ProvisioningClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningClient)) +@mock.patch.object(ProvisioningAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_provisioning_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + ProvisioningClient, ProvisioningAsyncClient +]) +@mock.patch.object(ProvisioningClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningClient)) +@mock.patch.object(ProvisioningAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningAsyncClient)) +def test_provisioning_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc"), + (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio"), + (ProvisioningClient, transports.ProvisioningRestTransport, "rest"), +]) +def test_provisioning_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", grpc_helpers), + (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (ProvisioningClient, transports.ProvisioningRestTransport, "rest", None), +]) +def test_provisioning_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_provisioning_client_client_options_from_dict(): + with mock.patch('google.cloud.apigee_registry_v1.services.provisioning.transports.ProvisioningGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = ProvisioningClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", grpc_helpers), + (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_provisioning_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "apigeeregistry.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="apigeeregistry.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + provisioning_service.CreateInstanceRequest, + dict, +]) +def test_create_instance(request_type, transport: str = 'grpc'): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instance_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 = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + client.create_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.CreateInstanceRequest() + +@pytest.mark.asyncio +async def test_create_instance_async(transport: str = 'grpc_asyncio', request_type=provisioning_service.CreateInstanceRequest): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.CreateInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instance_async_from_dict(): + await test_create_instance_async(request_type=dict) + + +def test_create_instance_field_headers(): + client = ProvisioningClient( + 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 = provisioning_service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_instance_field_headers_async(): + client = ProvisioningAsyncClient( + 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 = provisioning_service.CreateInstanceRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_instance_flattened(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_instance( + parent='parent_value', + instance=provisioning_service.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].instance + mock_val = provisioning_service.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + + +def test_create_instance_flattened_error(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_instance( + provisioning_service.CreateInstanceRequest(), + parent='parent_value', + instance=provisioning_service.Instance(name='name_value'), + instance_id='instance_id_value', + ) + +@pytest.mark.asyncio +async def test_create_instance_flattened_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_instance( + parent='parent_value', + instance=provisioning_service.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].instance + mock_val = provisioning_service.Instance(name='name_value') + assert arg == mock_val + arg = args[0].instance_id + mock_val = 'instance_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_instance_flattened_error_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_instance( + provisioning_service.CreateInstanceRequest(), + parent='parent_value', + instance=provisioning_service.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + provisioning_service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance(request_type, transport: str = 'grpc'): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_instance_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 = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + client.delete_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.DeleteInstanceRequest() + +@pytest.mark.asyncio +async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=provisioning_service.DeleteInstanceRequest): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + response = await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.DeleteInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) + + +def test_delete_instance_field_headers(): + client = ProvisioningClient( + 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 = provisioning_service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_instance_field_headers_async(): + client = ProvisioningAsyncClient( + 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 = provisioning_service.DeleteInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_instance_flattened(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_instance_flattened_error(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_instance( + provisioning_service.DeleteInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_instance_flattened_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/op') + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_instance_flattened_error_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_instance( + provisioning_service.DeleteInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + provisioning_service.GetInstanceRequest, + dict, +]) +def test_get_instance(request_type, transport: str = 'grpc'): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = provisioning_service.Instance( + name='name_value', + state=provisioning_service.Instance.State.INACTIVE, + state_message='state_message_value', + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, provisioning_service.Instance) + assert response.name == 'name_value' + assert response.state == provisioning_service.Instance.State.INACTIVE + assert response.state_message == 'state_message_value' + + +def test_get_instance_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 = ProvisioningClient( + 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_instance), + '__call__') as call: + client.get_instance() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.GetInstanceRequest() + +@pytest.mark.asyncio +async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=provisioning_service.GetInstanceRequest): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(provisioning_service.Instance( + name='name_value', + state=provisioning_service.Instance.State.INACTIVE, + state_message='state_message_value', + )) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == provisioning_service.GetInstanceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, provisioning_service.Instance) + assert response.name == 'name_value' + assert response.state == provisioning_service.Instance.State.INACTIVE + assert response.state_message == 'state_message_value' + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_field_headers(): + client = ProvisioningClient( + 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 = provisioning_service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = provisioning_service.Instance() + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_instance_field_headers_async(): + client = ProvisioningAsyncClient( + 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 = provisioning_service.GetInstanceRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(provisioning_service.Instance()) + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_instance_flattened(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = provisioning_service.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_instance_flattened_error(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + provisioning_service.GetInstanceRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_instance), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = provisioning_service.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(provisioning_service.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_instance_flattened_error_async(): + client = ProvisioningAsyncClient( + 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_instance( + provisioning_service.GetInstanceRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + provisioning_service.CreateInstanceRequest, + dict, +]) +def test_create_instance_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["instance"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 1, 'state_message': 'state_message_value', 'config': {'location': 'location_value', 'cmek_key_name': 'cmek_key_name_value'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_instance_rest_required_fields(request_type=provisioning_service.CreateInstanceRequest): + transport_class = transports.ProvisioningRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "instanceId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["instanceId"] = 'instance_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("instance_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == 'instance_id_value' + + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.ProvisioningRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("instanceId", )) & set(("parent", "instanceId", "instance", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.ProvisioningRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProvisioningRestInterceptor(), + ) + client = ProvisioningClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.ProvisioningRestInterceptor, "post_create_instance") as post, \ + mock.patch.object(transports.ProvisioningRestInterceptor, "pre_create_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = provisioning_service.CreateInstanceRequest.pb(provisioning_service.CreateInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = provisioning_service.CreateInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_instance_rest_bad_request(transport: str = 'rest', request_type=provisioning_service.CreateInstanceRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["instance"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 1, 'state_message': 'state_message_value', 'config': {'location': 'location_value', 'cmek_key_name': 'cmek_key_name_value'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_instance(request) + + +def test_create_instance_rest_flattened(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + instance=provisioning_service.Instance(name='name_value'), + instance_id='instance_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, args[1]) + + +def test_create_instance_rest_flattened_error(transport: str = 'rest'): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_instance( + provisioning_service.CreateInstanceRequest(), + parent='parent_value', + instance=provisioning_service.Instance(name='name_value'), + instance_id='instance_id_value', + ) + + +def test_create_instance_rest_error(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + provisioning_service.DeleteInstanceRequest, + dict, +]) +def test_delete_instance_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_delete_instance_rest_required_fields(request_type=provisioning_service.DeleteInstanceRequest): + transport_class = transports.ProvisioningRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.ProvisioningRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.ProvisioningRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProvisioningRestInterceptor(), + ) + client = ProvisioningClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(operation.Operation, "_set_result_from_operation"), \ + mock.patch.object(transports.ProvisioningRestInterceptor, "post_delete_instance") as post, \ + mock.patch.object(transports.ProvisioningRestInterceptor, "pre_delete_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = provisioning_service.DeleteInstanceRequest.pb(provisioning_service.DeleteInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) + + request = provisioning_service.DeleteInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request(transport: str = 'rest', request_type=provisioning_service.DeleteInstanceRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_instance(request) + + +def test_delete_instance_rest_flattened(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) + + +def test_delete_instance_rest_flattened_error(transport: str = 'rest'): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_instance( + provisioning_service.DeleteInstanceRequest(), + name='name_value', + ) + + +def test_delete_instance_rest_error(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + provisioning_service.GetInstanceRequest, + dict, +]) +def test_get_instance_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = provisioning_service.Instance( + name='name_value', + state=provisioning_service.Instance.State.INACTIVE, + state_message='state_message_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = provisioning_service.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, provisioning_service.Instance) + assert response.name == 'name_value' + assert response.state == provisioning_service.Instance.State.INACTIVE + assert response.state_message == 'state_message_value' + + +def test_get_instance_rest_required_fields(request_type=provisioning_service.GetInstanceRequest): + transport_class = transports.ProvisioningRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = provisioning_service.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = provisioning_service.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_instance(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.ProvisioningRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.ProvisioningRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ProvisioningRestInterceptor(), + ) + client = ProvisioningClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.ProvisioningRestInterceptor, "post_get_instance") as post, \ + mock.patch.object(transports.ProvisioningRestInterceptor, "pre_get_instance") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = provisioning_service.GetInstanceRequest.pb(provisioning_service.GetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = provisioning_service.Instance.to_json(provisioning_service.Instance()) + + request = provisioning_service.GetInstanceRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = provisioning_service.Instance() + + client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request(transport: str = 'rest', request_type=provisioning_service.GetInstanceRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_instance(request) + + +def test_get_instance_rest_flattened(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = provisioning_service.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/instances/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = provisioning_service.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) + + +def test_get_instance_rest_flattened_error(transport: str = 'rest'): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + provisioning_service.GetInstanceRequest(), + name='name_value', + ) + + +def test_get_instance_rest_error(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProvisioningGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProvisioningGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProvisioningClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProvisioningGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProvisioningClient( + 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 = ProvisioningClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProvisioningGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProvisioningClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProvisioningGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProvisioningClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProvisioningGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProvisioningGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.ProvisioningGrpcTransport, + transports.ProvisioningGrpcAsyncIOTransport, + transports.ProvisioningRestTransport, +]) +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", + "rest", +]) +def test_transport_kind(transport_name): + transport = ProvisioningClient.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 = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ProvisioningGrpcTransport, + ) + +def test_provisioning_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProvisioningTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_provisioning_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.apigee_registry_v1.services.provisioning.transports.ProvisioningTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.ProvisioningTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_instance', + 'delete_instance', + 'get_instance', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + '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_provisioning_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.apigee_registry_v1.services.provisioning.transports.ProvisioningTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProvisioningTransport( + 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_provisioning_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.apigee_registry_v1.services.provisioning.transports.ProvisioningTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProvisioningTransport() + adc.assert_called_once() + + +def test_provisioning_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) + ProvisioningClient() + 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.ProvisioningGrpcTransport, + transports.ProvisioningGrpcAsyncIOTransport, + ], +) +def test_provisioning_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.ProvisioningGrpcTransport, + transports.ProvisioningGrpcAsyncIOTransport, + transports.ProvisioningRestTransport, + ], +) +def test_provisioning_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.ProvisioningGrpcTransport, grpc_helpers), + (transports.ProvisioningGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_provisioning_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( + "apigeeregistry.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="apigeeregistry.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.ProvisioningGrpcTransport, transports.ProvisioningGrpcAsyncIOTransport]) +def test_provisioning_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 + ) + +def test_provisioning_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.ProvisioningRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_provisioning_rest_lro_client(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_provisioning_host_no_port(transport_name): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://apigeeregistry.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_provisioning_host_with_port(transport_name): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://apigeeregistry.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_provisioning_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProvisioningClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProvisioningClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_instance._session + session2 = client2.transport.create_instance._session + assert session1 != session2 + session1 = client1.transport.delete_instance._session + session2 = client2.transport.delete_instance._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 +def test_provisioning_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProvisioningGrpcTransport( + 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_provisioning_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ProvisioningGrpcAsyncIOTransport( + 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.ProvisioningGrpcTransport, transports.ProvisioningGrpcAsyncIOTransport]) +def test_provisioning_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.ProvisioningGrpcTransport, transports.ProvisioningGrpcAsyncIOTransport]) +def test_provisioning_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_provisioning_grpc_lro_client(): + client = ProvisioningClient( + 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_provisioning_grpc_lro_async_client(): + client = ProvisioningAsyncClient( + 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_instance_path(): + project = "squid" + location = "clam" + instance = "whelk" + expected = "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) + actual = ProvisioningClient.instance_path(project, location, instance) + assert expected == actual + + +def test_parse_instance_path(): + expected = { + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", + } + path = ProvisioningClient.instance_path(**expected) + + # Check that the path construction is reversible. + actual = ProvisioningClient.parse_instance_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = ProvisioningClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = ProvisioningClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProvisioningClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = ProvisioningClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = ProvisioningClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProvisioningClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = ProvisioningClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = ProvisioningClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProvisioningClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = ProvisioningClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = ProvisioningClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProvisioningClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = ProvisioningClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = ProvisioningClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProvisioningClient.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(transports.ProvisioningTransport, '_prep_wrapped_messages') as prep: + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ProvisioningTransport, '_prep_wrapped_messages') as prep: + transport_class = ProvisioningClient.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 = ProvisioningAsyncClient( + 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = ProvisioningClient( + 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 = ProvisioningAsyncClient( + 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 = ProvisioningClient( + 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 = ProvisioningAsyncClient( + 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 = ProvisioningClient( + 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 = ProvisioningAsyncClient( + 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 = ProvisioningClient( + 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 = ProvisioningAsyncClient( + 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 = ProvisioningClient( + 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 = ProvisioningAsyncClient( + 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"] + +def test_cancel_operation_from_dict(): + client = ProvisioningClient( + 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 + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = ProvisioningAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = ProvisioningClient( + 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.GetOperationRequest() + + # 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 + + # 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 = ProvisioningAsyncClient( + 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.GetOperationRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = ProvisioningClient( + 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.GetOperationRequest() + request.name = "locations" + + # 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() + + 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 + + # 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_get_operation_field_headers_async(): + client = ProvisioningAsyncClient( + 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.GetOperationRequest() + request.name = "locations" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + +def test_list_operations(transport: str = "grpc"): + client = ProvisioningClient( + 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.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 + + # 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 = ProvisioningAsyncClient( + 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.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 = 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = ProvisioningClient( + 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.ListOperationsRequest() + request.name = "locations" + + # 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() + + 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"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = ProvisioningAsyncClient( + 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.ListOperationsRequest() + request.name = "locations" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = ProvisioningClient( + 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 = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = ProvisioningAsyncClient( + 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_list_locations(transport: str = "grpc"): + client = ProvisioningClient( + 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 = locations_pb2.ListLocationsRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + client = ProvisioningAsyncClient( + 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 = locations_pb2.ListLocationsRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = ProvisioningClient( + 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.ListLocationsRequest() + request.name = "locations" + + # 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() + + 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"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = ProvisioningAsyncClient( + 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.ListLocationsRequest() + request.name = "locations" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = ProvisioningClient( + 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.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = ProvisioningAsyncClient( + 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_get_location(transport: str = "grpc"): + client = ProvisioningClient( + 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 = locations_pb2.GetLocationRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = ProvisioningAsyncClient( + 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 = locations_pb2.GetLocationRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = ProvisioningClient( + 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" + + # 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() + + 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"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = ProvisioningAsyncClient( + 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" + + # 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_get_location_from_dict(): + client = ProvisioningClient( + 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() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = ProvisioningAsyncClient( + 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.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = ProvisioningClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = ProvisioningAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = ProvisioningClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = ProvisioningAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = ProvisioningClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = ProvisioningAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = ProvisioningClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = ProvisioningAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = ProvisioningClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = ProvisioningAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = ProvisioningClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = ProvisioningAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = ProvisioningAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = ProvisioningClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (ProvisioningClient, transports.ProvisioningGrpcTransport), + (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py new file mode 100644 index 0000000..4f87d0d --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py @@ -0,0 +1,21303 @@ +# -*- 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. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable +from google.protobuf import json_format +import json +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +from google.api import httpbody_pb2 # type: ignore +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.apigee_registry_v1.services.registry import RegistryAsyncClient +from google.cloud.apigee_registry_v1.services.registry import RegistryClient +from google.cloud.apigee_registry_v1.services.registry import pagers +from google.cloud.apigee_registry_v1.services.registry import transports +from google.cloud.apigee_registry_v1.types import registry_models +from google.cloud.apigee_registry_v1.types import registry_service +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 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegistryClient._get_default_mtls_endpoint(None) is None + assert RegistryClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert RegistryClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert RegistryClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert RegistryClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert RegistryClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RegistryClient, "grpc"), + (RegistryAsyncClient, "grpc_asyncio"), + (RegistryClient, "rest"), +]) +def test_registry_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://apigeeregistry.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.RegistryGrpcTransport, "grpc"), + (transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RegistryRestTransport, "rest"), +]) +def test_registry_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (RegistryClient, "grpc"), + (RegistryAsyncClient, "grpc_asyncio"), + (RegistryClient, "rest"), +]) +def test_registry_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://apigeeregistry.googleapis.com' + ) + + +def test_registry_client_get_transport_class(): + transport = RegistryClient.get_transport_class() + available_transports = [ + transports.RegistryGrpcTransport, + transports.RegistryRestTransport, + ] + assert transport in available_transports + + transport = RegistryClient.get_transport_class("grpc") + assert transport == transports.RegistryGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistryClient, transports.RegistryGrpcTransport, "grpc"), + (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio"), + (RegistryClient, transports.RegistryRestTransport, "rest"), +]) +@mock.patch.object(RegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryClient)) +@mock.patch.object(RegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryAsyncClient)) +def test_registry_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RegistryClient, 'get_transport_class') as gtc: + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RegistryClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class(transport=transport_name) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError): + client = client_class(transport=transport_name) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (RegistryClient, transports.RegistryGrpcTransport, "grpc", "true"), + (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (RegistryClient, transports.RegistryGrpcTransport, "grpc", "false"), + (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (RegistryClient, transports.RegistryRestTransport, "rest", "true"), + (RegistryClient, transports.RegistryRestTransport, "rest", "false"), +]) +@mock.patch.object(RegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryClient)) +@mock.patch.object(RegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_registry_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client.DEFAULT_ENDPOINT + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + RegistryClient, RegistryAsyncClient +]) +@mock.patch.object(RegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryClient)) +@mock.patch.object(RegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryAsyncClient)) +def test_registry_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (RegistryClient, transports.RegistryGrpcTransport, "grpc"), + (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio"), + (RegistryClient, transports.RegistryRestTransport, "rest"), +]) +def test_registry_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegistryClient, transports.RegistryGrpcTransport, "grpc", grpc_helpers), + (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (RegistryClient, transports.RegistryRestTransport, "rest", None), +]) +def test_registry_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_registry_client_client_options_from_dict(): + with mock.patch('google.cloud.apigee_registry_v1.services.registry.transports.RegistryGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = RegistryClient( + client_options={'api_endpoint': 'squid.clam.whelk'} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (RegistryClient, transports.RegistryGrpcTransport, "grpc", grpc_helpers), + (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_registry_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "apigeeregistry.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + scopes=None, + default_host="apigeeregistry.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApisRequest, + dict, +]) +def test_list_apis(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApisResponse( + next_page_token='next_page_token_value', + ) + response = client.list_apis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApisRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApisPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_apis_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__') as call: + client.list_apis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApisRequest() + +@pytest.mark.asyncio +async def test_list_apis_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApisRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApisResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_apis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApisRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApisAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_apis_async_from_dict(): + await test_list_apis_async(request_type=dict) + + +def test_list_apis_field_headers(): + client = RegistryClient( + 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 = registry_service.ListApisRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__') as call: + call.return_value = registry_service.ListApisResponse() + client.list_apis(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_apis_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ListApisRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApisResponse()) + await client.list_apis(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_apis_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApisResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_apis( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_apis_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_apis( + registry_service.ListApisRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_apis_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApisResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApisResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_apis( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_apis_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_apis( + registry_service.ListApisRequest(), + parent='parent_value', + ) + + +def test_list_apis_pager(transport_name: str = "grpc"): + client = RegistryClient( + 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_apis), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + registry_models.Api(), + ], + next_page_token='abc', + ), + registry_service.ListApisResponse( + apis=[], + next_page_token='def', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + ], + next_page_token='ghi', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_apis(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.Api) + for i in results) +def test_list_apis_pages(transport_name: str = "grpc"): + client = RegistryClient( + 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_apis), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + registry_models.Api(), + ], + next_page_token='abc', + ), + registry_service.ListApisResponse( + apis=[], + next_page_token='def', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + ], + next_page_token='ghi', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + ], + ), + RuntimeError, + ) + pages = list(client.list_apis(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_apis_async_pager(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + registry_models.Api(), + ], + next_page_token='abc', + ), + registry_service.ListApisResponse( + apis=[], + next_page_token='def', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + ], + next_page_token='ghi', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_apis(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, registry_models.Api) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_apis_async_pages(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apis), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + registry_models.Api(), + ], + next_page_token='abc', + ), + registry_service.ListApisResponse( + apis=[], + next_page_token='def', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + ], + next_page_token='ghi', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_apis(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("request_type", [ + registry_service.GetApiRequest, + dict, +]) +def test_get_api(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + ) + response = client.get_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +def test_get_api_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 = RegistryClient( + 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_api), + '__call__') as call: + client.get_api() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiRequest() + +@pytest.mark.asyncio +async def test_get_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiRequest): + client = RegistryAsyncClient( + 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_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + )) + response = await client.get_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +@pytest.mark.asyncio +async def test_get_api_async_from_dict(): + await test_get_api_async(request_type=dict) + + +def test_get_api_field_headers(): + client = RegistryClient( + 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 = registry_service.GetApiRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api), + '__call__') as call: + call.return_value = registry_models.Api() + client.get_api(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_api_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.GetApiRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) + await client.get_api(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_api_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_api( + 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_api_flattened_error(): + client = RegistryClient( + 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_api( + registry_service.GetApiRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_api_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_api( + 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_api_flattened_error_async(): + client = RegistryAsyncClient( + 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_api( + registry_service.GetApiRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiRequest, + dict, +]) +def test_create_api(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + ) + response = client.create_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +def test_create_api_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api), + '__call__') as call: + client.create_api() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiRequest() + +@pytest.mark.asyncio +async def test_create_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + )) + response = await client.create_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +@pytest.mark.asyncio +async def test_create_api_async_from_dict(): + await test_create_api_async(request_type=dict) + + +def test_create_api_field_headers(): + client = RegistryClient( + 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 = registry_service.CreateApiRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api), + '__call__') as call: + call.return_value = registry_models.Api() + client.create_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_api_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.CreateApiRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) + await client.create_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_api_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_api( + parent='parent_value', + api=registry_models.Api(name='name_value'), + api_id='api_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api + mock_val = registry_models.Api(name='name_value') + assert arg == mock_val + arg = args[0].api_id + mock_val = 'api_id_value' + assert arg == mock_val + + +def test_create_api_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api( + registry_service.CreateApiRequest(), + parent='parent_value', + api=registry_models.Api(name='name_value'), + api_id='api_id_value', + ) + +@pytest.mark.asyncio +async def test_create_api_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_api( + parent='parent_value', + api=registry_models.Api(name='name_value'), + api_id='api_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api + mock_val = registry_models.Api(name='name_value') + assert arg == mock_val + arg = args[0].api_id + mock_val = 'api_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_api_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_api( + registry_service.CreateApiRequest(), + parent='parent_value', + api=registry_models.Api(name='name_value'), + api_id='api_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiRequest, + dict, +]) +def test_update_api(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + ) + response = client.update_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +def test_update_api_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api), + '__call__') as call: + client.update_api() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiRequest() + +@pytest.mark.asyncio +async def test_update_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + )) + response = await client.update_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +@pytest.mark.asyncio +async def test_update_api_async_from_dict(): + await test_update_api_async(request_type=dict) + + +def test_update_api_field_headers(): + client = RegistryClient( + 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 = registry_service.UpdateApiRequest() + + request.api.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api), + '__call__') as call: + call.return_value = registry_models.Api() + client.update_api(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', + 'api.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_api_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.UpdateApiRequest() + + request.api.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) + await client.update_api(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', + 'api.name=name_value', + ) in kw['metadata'] + + +def test_update_api_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_api( + api=registry_models.Api(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].api + mock_val = registry_models.Api(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_api_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api( + registry_service.UpdateApiRequest(), + api=registry_models.Api(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_api_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Api() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_api( + api=registry_models.Api(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].api + mock_val = registry_models.Api(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_api_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_api( + registry_service.UpdateApiRequest(), + api=registry_models.Api(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiRequest, + dict, +]) +def test_delete_api(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api), + '__call__') as call: + client.delete_api() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiRequest() + +@pytest.mark.asyncio +async def test_delete_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_api_async_from_dict(): + await test_delete_api_async(request_type=dict) + + +def test_delete_api_field_headers(): + client = RegistryClient( + 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 = registry_service.DeleteApiRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api), + '__call__') as call: + call.return_value = None + client.delete_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_api_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.DeleteApiRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_api(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_api_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_api( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_api_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api( + registry_service.DeleteApiRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_api_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_api( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_api_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_api( + registry_service.DeleteApiRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiVersionsRequest, + dict, +]) +def test_list_api_versions(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiVersionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_api_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_versions_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__') as call: + client.list_api_versions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiVersionsRequest() + +@pytest.mark.asyncio +async def test_list_api_versions_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiVersionsRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiVersionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_api_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiVersionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_api_versions_async_from_dict(): + await test_list_api_versions_async(request_type=dict) + + +def test_list_api_versions_field_headers(): + client = RegistryClient( + 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 = registry_service.ListApiVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__') as call: + call.return_value = registry_service.ListApiVersionsResponse() + client.list_api_versions(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_api_versions_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ListApiVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiVersionsResponse()) + await client.list_api_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_api_versions_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_api_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_api_versions_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_api_versions( + registry_service.ListApiVersionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_api_versions_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_api_versions( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_api_versions_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_api_versions( + registry_service.ListApiVersionsRequest(), + parent='parent_value', + ) + + +def test_list_api_versions_pager(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + next_page_token='abc', + ), + registry_service.ListApiVersionsResponse( + api_versions=[], + next_page_token='def', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + ], + next_page_token='ghi', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_api_versions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiVersion) + for i in results) +def test_list_api_versions_pages(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + next_page_token='abc', + ), + registry_service.ListApiVersionsResponse( + api_versions=[], + next_page_token='def', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + ], + next_page_token='ghi', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_api_versions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_api_versions_async_pager(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + next_page_token='abc', + ), + registry_service.ListApiVersionsResponse( + api_versions=[], + next_page_token='def', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + ], + next_page_token='ghi', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_api_versions(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, registry_models.ApiVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_api_versions_async_pages(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + next_page_token='abc', + ), + registry_service.ListApiVersionsResponse( + api_versions=[], + next_page_token='def', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + ], + next_page_token='ghi', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_api_versions(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("request_type", [ + registry_service.GetApiVersionRequest, + dict, +]) +def test_get_api_version(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + ) + response = client.get_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +def test_get_api_version_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 = RegistryClient( + 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_api_version), + '__call__') as call: + client.get_api_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiVersionRequest() + +@pytest.mark.asyncio +async def test_get_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiVersionRequest): + client = RegistryAsyncClient( + 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_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + )) + response = await client.get_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +@pytest.mark.asyncio +async def test_get_api_version_async_from_dict(): + await test_get_api_version_async(request_type=dict) + + +def test_get_api_version_field_headers(): + client = RegistryClient( + 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 = registry_service.GetApiVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_version), + '__call__') as call: + call.return_value = registry_models.ApiVersion() + client.get_api_version(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_api_version_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.GetApiVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) + await client.get_api_version(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_api_version_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_api_version( + 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_api_version_flattened_error(): + client = RegistryClient( + 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_api_version( + registry_service.GetApiVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_api_version_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_api_version( + 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_api_version_flattened_error_async(): + client = RegistryAsyncClient( + 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_api_version( + registry_service.GetApiVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiVersionRequest, + dict, +]) +def test_create_api_version(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + ) + response = client.create_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +def test_create_api_version_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_version), + '__call__') as call: + client.create_api_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiVersionRequest() + +@pytest.mark.asyncio +async def test_create_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiVersionRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + )) + response = await client.create_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +@pytest.mark.asyncio +async def test_create_api_version_async_from_dict(): + await test_create_api_version_async(request_type=dict) + + +def test_create_api_version_field_headers(): + client = RegistryClient( + 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 = registry_service.CreateApiVersionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_version), + '__call__') as call: + call.return_value = registry_models.ApiVersion() + client.create_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_api_version_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.CreateApiVersionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) + await client.create_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_api_version_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_api_version( + parent='parent_value', + api_version=registry_models.ApiVersion(name='name_value'), + api_version_id='api_version_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api_version + mock_val = registry_models.ApiVersion(name='name_value') + assert arg == mock_val + arg = args[0].api_version_id + mock_val = 'api_version_id_value' + assert arg == mock_val + + +def test_create_api_version_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api_version( + registry_service.CreateApiVersionRequest(), + parent='parent_value', + api_version=registry_models.ApiVersion(name='name_value'), + api_version_id='api_version_id_value', + ) + +@pytest.mark.asyncio +async def test_create_api_version_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_api_version( + parent='parent_value', + api_version=registry_models.ApiVersion(name='name_value'), + api_version_id='api_version_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api_version + mock_val = registry_models.ApiVersion(name='name_value') + assert arg == mock_val + arg = args[0].api_version_id + mock_val = 'api_version_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_api_version_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_api_version( + registry_service.CreateApiVersionRequest(), + parent='parent_value', + api_version=registry_models.ApiVersion(name='name_value'), + api_version_id='api_version_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiVersionRequest, + dict, +]) +def test_update_api_version(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + ) + response = client.update_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +def test_update_api_version_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_version), + '__call__') as call: + client.update_api_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiVersionRequest() + +@pytest.mark.asyncio +async def test_update_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiVersionRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + )) + response = await client.update_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +@pytest.mark.asyncio +async def test_update_api_version_async_from_dict(): + await test_update_api_version_async(request_type=dict) + + +def test_update_api_version_field_headers(): + client = RegistryClient( + 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 = registry_service.UpdateApiVersionRequest() + + request.api_version.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_version), + '__call__') as call: + call.return_value = registry_models.ApiVersion() + client.update_api_version(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', + 'api_version.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_api_version_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.UpdateApiVersionRequest() + + request.api_version.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) + await client.update_api_version(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', + 'api_version.name=name_value', + ) in kw['metadata'] + + +def test_update_api_version_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_api_version( + api_version=registry_models.ApiVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].api_version + mock_val = registry_models.ApiVersion(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_api_version_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api_version( + registry_service.UpdateApiVersionRequest(), + api_version=registry_models.ApiVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_api_version_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_api_version( + api_version=registry_models.ApiVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].api_version + mock_val = registry_models.ApiVersion(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_api_version_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_api_version( + registry_service.UpdateApiVersionRequest(), + api_version=registry_models.ApiVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiVersionRequest, + dict, +]) +def test_delete_api_version(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_version_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_version), + '__call__') as call: + client.delete_api_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiVersionRequest() + +@pytest.mark.asyncio +async def test_delete_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiVersionRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiVersionRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_api_version_async_from_dict(): + await test_delete_api_version_async(request_type=dict) + + +def test_delete_api_version_field_headers(): + client = RegistryClient( + 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 = registry_service.DeleteApiVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_version), + '__call__') as call: + call.return_value = None + client.delete_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_api_version_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.DeleteApiVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_api_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_api_version_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_api_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_api_version_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_version( + registry_service.DeleteApiVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_api_version_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_api_version( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_api_version_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_api_version( + registry_service.DeleteApiVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiSpecsRequest, + dict, +]) +def test_list_api_specs(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiSpecsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_api_specs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiSpecsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiSpecsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_specs_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__') as call: + client.list_api_specs() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiSpecsRequest() + +@pytest.mark.asyncio +async def test_list_api_specs_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiSpecsRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_api_specs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiSpecsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiSpecsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_api_specs_async_from_dict(): + await test_list_api_specs_async(request_type=dict) + + +def test_list_api_specs_field_headers(): + client = RegistryClient( + 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 = registry_service.ListApiSpecsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__') as call: + call.return_value = registry_service.ListApiSpecsResponse() + client.list_api_specs(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_api_specs_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ListApiSpecsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecsResponse()) + await client.list_api_specs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_api_specs_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiSpecsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_api_specs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_api_specs_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_api_specs( + registry_service.ListApiSpecsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_api_specs_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiSpecsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_api_specs( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_api_specs_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_api_specs( + registry_service.ListApiSpecsRequest(), + parent='parent_value', + ) + + +def test_list_api_specs_pager(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_specs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_api_specs(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiSpec) + for i in results) +def test_list_api_specs_pages(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_specs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + pages = list(client.list_api_specs(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_api_specs_async_pager(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_api_specs(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, registry_models.ApiSpec) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_api_specs_async_pages(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_specs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_api_specs(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("request_type", [ + registry_service.GetApiSpecRequest, + dict, +]) +def test_get_api_spec(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + response = client.get_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_get_api_spec_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 = RegistryClient( + 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_api_spec), + '__call__') as call: + client.get_api_spec() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiSpecRequest() + +@pytest.mark.asyncio +async def test_get_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiSpecRequest): + client = RegistryAsyncClient( + 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_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + )) + response = await client.get_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_get_api_spec_async_from_dict(): + await test_get_api_spec_async(request_type=dict) + + +def test_get_api_spec_field_headers(): + client = RegistryClient( + 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 = registry_service.GetApiSpecRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec), + '__call__') as call: + call.return_value = registry_models.ApiSpec() + client.get_api_spec(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_api_spec_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.GetApiSpecRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + await client.get_api_spec(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_api_spec_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_api_spec( + 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_api_spec_flattened_error(): + client = RegistryClient( + 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_api_spec( + registry_service.GetApiSpecRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_api_spec_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_api_spec( + 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_api_spec_flattened_error_async(): + client = RegistryAsyncClient( + 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_api_spec( + registry_service.GetApiSpecRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetApiSpecContentsRequest, + dict, +]) +def test_get_api_spec_contents(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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_api_spec_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.get_api_spec_contents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiSpecContentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_get_api_spec_contents_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 = RegistryClient( + 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_api_spec_contents), + '__call__') as call: + client.get_api_spec_contents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiSpecContentsRequest() + +@pytest.mark.asyncio +async def test_get_api_spec_contents_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiSpecContentsRequest): + client = RegistryAsyncClient( + 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_api_spec_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.get_api_spec_contents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiSpecContentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_get_api_spec_contents_async_from_dict(): + await test_get_api_spec_contents_async(request_type=dict) + + +def test_get_api_spec_contents_field_headers(): + client = RegistryClient( + 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 = registry_service.GetApiSpecContentsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec_contents), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.get_api_spec_contents(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_api_spec_contents_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.GetApiSpecContentsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec_contents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.get_api_spec_contents(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_api_spec_contents_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_api_spec_contents( + 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_api_spec_contents_flattened_error(): + client = RegistryClient( + 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_api_spec_contents( + registry_service.GetApiSpecContentsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_api_spec_contents_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_spec_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_api_spec_contents( + 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_api_spec_contents_flattened_error_async(): + client = RegistryAsyncClient( + 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_api_spec_contents( + registry_service.GetApiSpecContentsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiSpecRequest, + dict, +]) +def test_create_api_spec(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + response = client.create_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_create_api_spec_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_spec), + '__call__') as call: + client.create_api_spec() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiSpecRequest() + +@pytest.mark.asyncio +async def test_create_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiSpecRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + )) + response = await client.create_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_create_api_spec_async_from_dict(): + await test_create_api_spec_async(request_type=dict) + + +def test_create_api_spec_field_headers(): + client = RegistryClient( + 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 = registry_service.CreateApiSpecRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_spec), + '__call__') as call: + call.return_value = registry_models.ApiSpec() + client.create_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_api_spec_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.CreateApiSpecRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_spec), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + await client.create_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_api_spec_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_api_spec( + parent='parent_value', + api_spec=registry_models.ApiSpec(name='name_value'), + api_spec_id='api_spec_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api_spec + mock_val = registry_models.ApiSpec(name='name_value') + assert arg == mock_val + arg = args[0].api_spec_id + mock_val = 'api_spec_id_value' + assert arg == mock_val + + +def test_create_api_spec_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api_spec( + registry_service.CreateApiSpecRequest(), + parent='parent_value', + api_spec=registry_models.ApiSpec(name='name_value'), + api_spec_id='api_spec_id_value', + ) + +@pytest.mark.asyncio +async def test_create_api_spec_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_api_spec( + parent='parent_value', + api_spec=registry_models.ApiSpec(name='name_value'), + api_spec_id='api_spec_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api_spec + mock_val = registry_models.ApiSpec(name='name_value') + assert arg == mock_val + arg = args[0].api_spec_id + mock_val = 'api_spec_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_api_spec_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_api_spec( + registry_service.CreateApiSpecRequest(), + parent='parent_value', + api_spec=registry_models.ApiSpec(name='name_value'), + api_spec_id='api_spec_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiSpecRequest, + dict, +]) +def test_update_api_spec(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + response = client.update_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_update_api_spec_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_spec), + '__call__') as call: + client.update_api_spec() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiSpecRequest() + +@pytest.mark.asyncio +async def test_update_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiSpecRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + )) + response = await client.update_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_update_api_spec_async_from_dict(): + await test_update_api_spec_async(request_type=dict) + + +def test_update_api_spec_field_headers(): + client = RegistryClient( + 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 = registry_service.UpdateApiSpecRequest() + + request.api_spec.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_spec), + '__call__') as call: + call.return_value = registry_models.ApiSpec() + client.update_api_spec(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', + 'api_spec.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_api_spec_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.UpdateApiSpecRequest() + + request.api_spec.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_spec), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + await client.update_api_spec(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', + 'api_spec.name=name_value', + ) in kw['metadata'] + + +def test_update_api_spec_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_api_spec( + api_spec=registry_models.ApiSpec(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].api_spec + mock_val = registry_models.ApiSpec(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_api_spec_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api_spec( + registry_service.UpdateApiSpecRequest(), + api_spec=registry_models.ApiSpec(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_api_spec_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_api_spec( + api_spec=registry_models.ApiSpec(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].api_spec + mock_val = registry_models.ApiSpec(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_api_spec_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_api_spec( + registry_service.UpdateApiSpecRequest(), + api_spec=registry_models.ApiSpec(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiSpecRequest, + dict, +]) +def test_delete_api_spec(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiSpecRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_spec_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec), + '__call__') as call: + client.delete_api_spec() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiSpecRequest() + +@pytest.mark.asyncio +async def test_delete_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiSpecRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiSpecRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_api_spec_async_from_dict(): + await test_delete_api_spec_async(request_type=dict) + + +def test_delete_api_spec_field_headers(): + client = RegistryClient( + 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 = registry_service.DeleteApiSpecRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec), + '__call__') as call: + call.return_value = None + client.delete_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_api_spec_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.DeleteApiSpecRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_api_spec_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_api_spec( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_api_spec_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_spec( + registry_service.DeleteApiSpecRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_api_spec_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_api_spec( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_api_spec_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_api_spec( + registry_service.DeleteApiSpecRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.TagApiSpecRevisionRequest, + dict, +]) +def test_tag_api_spec_revision(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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.tag_api_spec_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + response = client.tag_api_spec_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.TagApiSpecRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_tag_api_spec_revision_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 = RegistryClient( + 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.tag_api_spec_revision), + '__call__') as call: + client.tag_api_spec_revision() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.TagApiSpecRevisionRequest() + +@pytest.mark.asyncio +async def test_tag_api_spec_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.TagApiSpecRevisionRequest): + client = RegistryAsyncClient( + 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.tag_api_spec_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + )) + response = await client.tag_api_spec_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.TagApiSpecRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_tag_api_spec_revision_async_from_dict(): + await test_tag_api_spec_revision_async(request_type=dict) + + +def test_tag_api_spec_revision_field_headers(): + client = RegistryClient( + 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 = registry_service.TagApiSpecRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tag_api_spec_revision), + '__call__') as call: + call.return_value = registry_models.ApiSpec() + client.tag_api_spec_revision(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_tag_api_spec_revision_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.TagApiSpecRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tag_api_spec_revision), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + await client.tag_api_spec_revision(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'] + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiSpecRevisionsRequest, + dict, +]) +def test_list_api_spec_revisions(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_spec_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiSpecRevisionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_api_spec_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiSpecRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiSpecRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_spec_revisions_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_spec_revisions), + '__call__') as call: + client.list_api_spec_revisions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiSpecRevisionsRequest() + +@pytest.mark.asyncio +async def test_list_api_spec_revisions_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiSpecRevisionsRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_spec_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecRevisionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_api_spec_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiSpecRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiSpecRevisionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_api_spec_revisions_async_from_dict(): + await test_list_api_spec_revisions_async(request_type=dict) + + +def test_list_api_spec_revisions_field_headers(): + client = RegistryClient( + 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 = registry_service.ListApiSpecRevisionsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_spec_revisions), + '__call__') as call: + call.return_value = registry_service.ListApiSpecRevisionsResponse() + client.list_api_spec_revisions(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_list_api_spec_revisions_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ListApiSpecRevisionsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_spec_revisions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecRevisionsResponse()) + await client.list_api_spec_revisions(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_list_api_spec_revisions_pager(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_spec_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.list_api_spec_revisions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiSpec) + for i in results) +def test_list_api_spec_revisions_pages(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_spec_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + pages = list(client.list_api_spec_revisions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_api_spec_revisions_async_pager(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_spec_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_api_spec_revisions(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, registry_models.ApiSpec) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_api_spec_revisions_async_pages(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_spec_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_api_spec_revisions(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("request_type", [ + registry_service.RollbackApiSpecRequest, + dict, +]) +def test_rollback_api_spec(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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.rollback_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + response = client.rollback_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.RollbackApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_rollback_api_spec_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 = RegistryClient( + 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.rollback_api_spec), + '__call__') as call: + client.rollback_api_spec() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.RollbackApiSpecRequest() + +@pytest.mark.asyncio +async def test_rollback_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.RollbackApiSpecRequest): + client = RegistryAsyncClient( + 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.rollback_api_spec), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + )) + response = await client.rollback_api_spec(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.RollbackApiSpecRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_rollback_api_spec_async_from_dict(): + await test_rollback_api_spec_async(request_type=dict) + + +def test_rollback_api_spec_field_headers(): + client = RegistryClient( + 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 = registry_service.RollbackApiSpecRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_api_spec), + '__call__') as call: + call.return_value = registry_models.ApiSpec() + client.rollback_api_spec(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_rollback_api_spec_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.RollbackApiSpecRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_api_spec), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + await client.rollback_api_spec(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'] + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiSpecRevisionRequest, + dict, +]) +def test_delete_api_spec_revision(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + response = client.delete_api_spec_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiSpecRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_delete_api_spec_revision_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec_revision), + '__call__') as call: + client.delete_api_spec_revision() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiSpecRevisionRequest() + +@pytest.mark.asyncio +async def test_delete_api_spec_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiSpecRevisionRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + )) + response = await client.delete_api_spec_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiSpecRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_delete_api_spec_revision_async_from_dict(): + await test_delete_api_spec_revision_async(request_type=dict) + + +def test_delete_api_spec_revision_field_headers(): + client = RegistryClient( + 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 = registry_service.DeleteApiSpecRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec_revision), + '__call__') as call: + call.return_value = registry_models.ApiSpec() + client.delete_api_spec_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_api_spec_revision_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.DeleteApiSpecRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec_revision), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + await client.delete_api_spec_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_api_spec_revision_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_api_spec_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_api_spec_revision_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_spec_revision( + registry_service.DeleteApiSpecRevisionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_api_spec_revision_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_spec_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiSpec() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_api_spec_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_api_spec_revision_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_api_spec_revision( + registry_service.DeleteApiSpecRevisionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiDeploymentsRequest, + dict, +]) +def test_list_api_deployments(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiDeploymentsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_api_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiDeploymentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiDeploymentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_deployments_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__') as call: + client.list_api_deployments() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiDeploymentsRequest() + +@pytest.mark.asyncio +async def test_list_api_deployments_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiDeploymentsRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_api_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiDeploymentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiDeploymentsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_api_deployments_async_from_dict(): + await test_list_api_deployments_async(request_type=dict) + + +def test_list_api_deployments_field_headers(): + client = RegistryClient( + 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 = registry_service.ListApiDeploymentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__') as call: + call.return_value = registry_service.ListApiDeploymentsResponse() + client.list_api_deployments(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_api_deployments_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ListApiDeploymentsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentsResponse()) + await client.list_api_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_api_deployments_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiDeploymentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_api_deployments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_api_deployments_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_api_deployments( + registry_service.ListApiDeploymentsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_api_deployments_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiDeploymentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_api_deployments( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_api_deployments_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_api_deployments( + registry_service.ListApiDeploymentsRequest(), + parent='parent_value', + ) + + +def test_list_api_deployments_pager(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_deployments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_api_deployments(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiDeployment) + for i in results) +def test_list_api_deployments_pages(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_deployments), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_api_deployments(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_api_deployments_async_pager(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_api_deployments(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, registry_models.ApiDeployment) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_api_deployments_async_pages(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployments), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_api_deployments(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("request_type", [ + registry_service.GetApiDeploymentRequest, + dict, +]) +def test_get_api_deployment(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + response = client.get_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_get_api_deployment_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 = RegistryClient( + 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_api_deployment), + '__call__') as call: + client.get_api_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiDeploymentRequest() + +@pytest.mark.asyncio +async def test_get_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiDeploymentRequest): + client = RegistryAsyncClient( + 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_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + )) + response = await client.get_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +@pytest.mark.asyncio +async def test_get_api_deployment_async_from_dict(): + await test_get_api_deployment_async(request_type=dict) + + +def test_get_api_deployment_field_headers(): + client = RegistryClient( + 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 = registry_service.GetApiDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_deployment), + '__call__') as call: + call.return_value = registry_models.ApiDeployment() + client.get_api_deployment(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_api_deployment_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.GetApiDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + await client.get_api_deployment(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_api_deployment_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_api_deployment( + 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_api_deployment_flattened_error(): + client = RegistryClient( + 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_api_deployment( + registry_service.GetApiDeploymentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_api_deployment_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_api_deployment( + 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_api_deployment_flattened_error_async(): + client = RegistryAsyncClient( + 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_api_deployment( + registry_service.GetApiDeploymentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiDeploymentRequest, + dict, +]) +def test_create_api_deployment(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + response = client.create_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_create_api_deployment_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_deployment), + '__call__') as call: + client.create_api_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiDeploymentRequest() + +@pytest.mark.asyncio +async def test_create_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiDeploymentRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + )) + response = await client.create_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +@pytest.mark.asyncio +async def test_create_api_deployment_async_from_dict(): + await test_create_api_deployment_async(request_type=dict) + + +def test_create_api_deployment_field_headers(): + client = RegistryClient( + 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 = registry_service.CreateApiDeploymentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_deployment), + '__call__') as call: + call.return_value = registry_models.ApiDeployment() + client.create_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_api_deployment_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.CreateApiDeploymentRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + await client.create_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_api_deployment_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_api_deployment( + parent='parent_value', + api_deployment=registry_models.ApiDeployment(name='name_value'), + api_deployment_id='api_deployment_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api_deployment + mock_val = registry_models.ApiDeployment(name='name_value') + assert arg == mock_val + arg = args[0].api_deployment_id + mock_val = 'api_deployment_id_value' + assert arg == mock_val + + +def test_create_api_deployment_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api_deployment( + registry_service.CreateApiDeploymentRequest(), + parent='parent_value', + api_deployment=registry_models.ApiDeployment(name='name_value'), + api_deployment_id='api_deployment_id_value', + ) + +@pytest.mark.asyncio +async def test_create_api_deployment_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_api_deployment( + parent='parent_value', + api_deployment=registry_models.ApiDeployment(name='name_value'), + api_deployment_id='api_deployment_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].api_deployment + mock_val = registry_models.ApiDeployment(name='name_value') + assert arg == mock_val + arg = args[0].api_deployment_id + mock_val = 'api_deployment_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_api_deployment_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_api_deployment( + registry_service.CreateApiDeploymentRequest(), + parent='parent_value', + api_deployment=registry_models.ApiDeployment(name='name_value'), + api_deployment_id='api_deployment_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiDeploymentRequest, + dict, +]) +def test_update_api_deployment(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + response = client.update_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_update_api_deployment_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_deployment), + '__call__') as call: + client.update_api_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiDeploymentRequest() + +@pytest.mark.asyncio +async def test_update_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiDeploymentRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + )) + response = await client.update_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.UpdateApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +@pytest.mark.asyncio +async def test_update_api_deployment_async_from_dict(): + await test_update_api_deployment_async(request_type=dict) + + +def test_update_api_deployment_field_headers(): + client = RegistryClient( + 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 = registry_service.UpdateApiDeploymentRequest() + + request.api_deployment.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_deployment), + '__call__') as call: + call.return_value = registry_models.ApiDeployment() + client.update_api_deployment(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', + 'api_deployment.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_api_deployment_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.UpdateApiDeploymentRequest() + + request.api_deployment.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + await client.update_api_deployment(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', + 'api_deployment.name=name_value', + ) in kw['metadata'] + + +def test_update_api_deployment_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_api_deployment( + api_deployment=registry_models.ApiDeployment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].api_deployment + mock_val = registry_models.ApiDeployment(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + + +def test_update_api_deployment_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api_deployment( + registry_service.UpdateApiDeploymentRequest(), + api_deployment=registry_models.ApiDeployment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_api_deployment_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_api_deployment( + api_deployment=registry_models.ApiDeployment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].api_deployment + mock_val = registry_models.ApiDeployment(name='name_value') + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_api_deployment_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_api_deployment( + registry_service.UpdateApiDeploymentRequest(), + api_deployment=registry_models.ApiDeployment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiDeploymentRequest, + dict, +]) +def test_delete_api_deployment(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_deployment_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment), + '__call__') as call: + client.delete_api_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiDeploymentRequest() + +@pytest.mark.asyncio +async def test_delete_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiDeploymentRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_api_deployment_async_from_dict(): + await test_delete_api_deployment_async(request_type=dict) + + +def test_delete_api_deployment_field_headers(): + client = RegistryClient( + 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 = registry_service.DeleteApiDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment), + '__call__') as call: + call.return_value = None + client.delete_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_api_deployment_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.DeleteApiDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_api_deployment_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_api_deployment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_api_deployment_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_deployment( + registry_service.DeleteApiDeploymentRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_api_deployment_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_api_deployment( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_api_deployment_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_api_deployment( + registry_service.DeleteApiDeploymentRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.TagApiDeploymentRevisionRequest, + dict, +]) +def test_tag_api_deployment_revision(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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.tag_api_deployment_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + response = client.tag_api_deployment_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.TagApiDeploymentRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_tag_api_deployment_revision_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 = RegistryClient( + 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.tag_api_deployment_revision), + '__call__') as call: + client.tag_api_deployment_revision() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.TagApiDeploymentRevisionRequest() + +@pytest.mark.asyncio +async def test_tag_api_deployment_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.TagApiDeploymentRevisionRequest): + client = RegistryAsyncClient( + 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.tag_api_deployment_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + )) + response = await client.tag_api_deployment_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.TagApiDeploymentRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +@pytest.mark.asyncio +async def test_tag_api_deployment_revision_async_from_dict(): + await test_tag_api_deployment_revision_async(request_type=dict) + + +def test_tag_api_deployment_revision_field_headers(): + client = RegistryClient( + 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 = registry_service.TagApiDeploymentRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tag_api_deployment_revision), + '__call__') as call: + call.return_value = registry_models.ApiDeployment() + client.tag_api_deployment_revision(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_tag_api_deployment_revision_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.TagApiDeploymentRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.tag_api_deployment_revision), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + await client.tag_api_deployment_revision(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'] + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiDeploymentRevisionsRequest, + dict, +]) +def test_list_api_deployment_revisions(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployment_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListApiDeploymentRevisionsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_api_deployment_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiDeploymentRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiDeploymentRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_deployment_revisions_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployment_revisions), + '__call__') as call: + client.list_api_deployment_revisions() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiDeploymentRevisionsRequest() + +@pytest.mark.asyncio +async def test_list_api_deployment_revisions_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiDeploymentRevisionsRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployment_revisions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentRevisionsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_api_deployment_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListApiDeploymentRevisionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiDeploymentRevisionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_api_deployment_revisions_async_from_dict(): + await test_list_api_deployment_revisions_async(request_type=dict) + + +def test_list_api_deployment_revisions_field_headers(): + client = RegistryClient( + 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 = registry_service.ListApiDeploymentRevisionsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployment_revisions), + '__call__') as call: + call.return_value = registry_service.ListApiDeploymentRevisionsResponse() + client.list_api_deployment_revisions(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_list_api_deployment_revisions_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ListApiDeploymentRevisionsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployment_revisions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentRevisionsResponse()) + await client.list_api_deployment_revisions(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_list_api_deployment_revisions_pager(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_deployment_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('name', ''), + )), + ) + pager = client.list_api_deployment_revisions(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiDeployment) + for i in results) +def test_list_api_deployment_revisions_pages(transport_name: str = "grpc"): + client = RegistryClient( + 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_api_deployment_revisions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_api_deployment_revisions(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_api_deployment_revisions_async_pager(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployment_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_api_deployment_revisions(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, registry_models.ApiDeployment) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_api_deployment_revisions_async_pages(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_api_deployment_revisions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_api_deployment_revisions(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("request_type", [ + registry_service.RollbackApiDeploymentRequest, + dict, +]) +def test_rollback_api_deployment(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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.rollback_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + response = client.rollback_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.RollbackApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_rollback_api_deployment_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 = RegistryClient( + 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.rollback_api_deployment), + '__call__') as call: + client.rollback_api_deployment() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.RollbackApiDeploymentRequest() + +@pytest.mark.asyncio +async def test_rollback_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.RollbackApiDeploymentRequest): + client = RegistryAsyncClient( + 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.rollback_api_deployment), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + )) + response = await client.rollback_api_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.RollbackApiDeploymentRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +@pytest.mark.asyncio +async def test_rollback_api_deployment_async_from_dict(): + await test_rollback_api_deployment_async(request_type=dict) + + +def test_rollback_api_deployment_field_headers(): + client = RegistryClient( + 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 = registry_service.RollbackApiDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_api_deployment), + '__call__') as call: + call.return_value = registry_models.ApiDeployment() + client.rollback_api_deployment(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_rollback_api_deployment_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.RollbackApiDeploymentRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.rollback_api_deployment), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + await client.rollback_api_deployment(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'] + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiDeploymentRevisionRequest, + dict, +]) +def test_delete_api_deployment_revision(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + response = client.delete_api_deployment_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiDeploymentRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_delete_api_deployment_revision_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment_revision), + '__call__') as call: + client.delete_api_deployment_revision() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiDeploymentRevisionRequest() + +@pytest.mark.asyncio +async def test_delete_api_deployment_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiDeploymentRevisionRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + )) + response = await client.delete_api_deployment_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteApiDeploymentRevisionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +@pytest.mark.asyncio +async def test_delete_api_deployment_revision_async_from_dict(): + await test_delete_api_deployment_revision_async(request_type=dict) + + +def test_delete_api_deployment_revision_field_headers(): + client = RegistryClient( + 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 = registry_service.DeleteApiDeploymentRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment_revision), + '__call__') as call: + call.return_value = registry_models.ApiDeployment() + client.delete_api_deployment_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_api_deployment_revision_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.DeleteApiDeploymentRevisionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment_revision), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + await client.delete_api_deployment_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_api_deployment_revision_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_api_deployment_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_api_deployment_revision_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_deployment_revision( + registry_service.DeleteApiDeploymentRevisionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_api_deployment_revision_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_api_deployment_revision), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.ApiDeployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_api_deployment_revision( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_api_deployment_revision_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_api_deployment_revision( + registry_service.DeleteApiDeploymentRevisionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListArtifactsRequest, + dict, +]) +def test_list_artifacts(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListArtifactsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_artifacts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListArtifactsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListArtifactsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_artifacts_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__') as call: + client.list_artifacts() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListArtifactsRequest() + +@pytest.mark.asyncio +async def test_list_artifacts_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListArtifactsRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListArtifactsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_artifacts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ListArtifactsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListArtifactsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_artifacts_async_from_dict(): + await test_list_artifacts_async(request_type=dict) + + +def test_list_artifacts_field_headers(): + client = RegistryClient( + 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 = registry_service.ListArtifactsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__') as call: + call.return_value = registry_service.ListArtifactsResponse() + client.list_artifacts(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_artifacts_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ListArtifactsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListArtifactsResponse()) + await client.list_artifacts(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_artifacts_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListArtifactsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_artifacts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + + +def test_list_artifacts_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_artifacts( + registry_service.ListArtifactsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_artifacts_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_service.ListArtifactsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListArtifactsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_artifacts( + parent='parent_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_list_artifacts_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_artifacts( + registry_service.ListArtifactsRequest(), + parent='parent_value', + ) + + +def test_list_artifacts_pager(transport_name: str = "grpc"): + client = RegistryClient( + 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_artifacts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + registry_models.Artifact(), + ], + next_page_token='abc', + ), + registry_service.ListArtifactsResponse( + artifacts=[], + next_page_token='def', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + ], + next_page_token='ghi', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_artifacts(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.Artifact) + for i in results) +def test_list_artifacts_pages(transport_name: str = "grpc"): + client = RegistryClient( + 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_artifacts), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + registry_models.Artifact(), + ], + next_page_token='abc', + ), + registry_service.ListArtifactsResponse( + artifacts=[], + next_page_token='def', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + ], + next_page_token='ghi', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + ], + ), + RuntimeError, + ) + pages = list(client.list_artifacts(request={}).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.asyncio +async def test_list_artifacts_async_pager(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + registry_models.Artifact(), + ], + next_page_token='abc', + ), + registry_service.ListArtifactsResponse( + artifacts=[], + next_page_token='def', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + ], + next_page_token='ghi', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_artifacts(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, registry_models.Artifact) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_artifacts_async_pages(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_artifacts), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + registry_models.Artifact(), + ], + next_page_token='abc', + ), + registry_service.ListArtifactsResponse( + artifacts=[], + next_page_token='def', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + ], + next_page_token='ghi', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_artifacts(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("request_type", [ + registry_service.GetArtifactRequest, + dict, +]) +def test_get_artifact(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + ) + response = client.get_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetArtifactRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +def test_get_artifact_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 = RegistryClient( + 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_artifact), + '__call__') as call: + client.get_artifact() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetArtifactRequest() + +@pytest.mark.asyncio +async def test_get_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetArtifactRequest): + client = RegistryAsyncClient( + 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_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + )) + response = await client.get_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetArtifactRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_get_artifact_async_from_dict(): + await test_get_artifact_async(request_type=dict) + + +def test_get_artifact_field_headers(): + client = RegistryClient( + 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 = registry_service.GetArtifactRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact), + '__call__') as call: + call.return_value = registry_models.Artifact() + client.get_artifact(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_artifact_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.GetArtifactRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) + await client.get_artifact(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_artifact_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_artifact( + 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_artifact_flattened_error(): + client = RegistryClient( + 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_artifact( + registry_service.GetArtifactRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_artifact_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_artifact( + 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_artifact_flattened_error_async(): + client = RegistryAsyncClient( + 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_artifact( + registry_service.GetArtifactRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetArtifactContentsRequest, + dict, +]) +def test_get_artifact_contents(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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_artifact_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + response = client.get_artifact_contents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetArtifactContentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_get_artifact_contents_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 = RegistryClient( + 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_artifact_contents), + '__call__') as call: + client.get_artifact_contents() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetArtifactContentsRequest() + +@pytest.mark.asyncio +async def test_get_artifact_contents_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetArtifactContentsRequest): + client = RegistryAsyncClient( + 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_artifact_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + )) + response = await client.get_artifact_contents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.GetArtifactContentsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_get_artifact_contents_async_from_dict(): + await test_get_artifact_contents_async(request_type=dict) + + +def test_get_artifact_contents_field_headers(): + client = RegistryClient( + 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 = registry_service.GetArtifactContentsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact_contents), + '__call__') as call: + call.return_value = httpbody_pb2.HttpBody() + client.get_artifact_contents(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_artifact_contents_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.GetArtifactContentsRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact_contents), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + await client.get_artifact_contents(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_artifact_contents_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_artifact_contents( + 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_artifact_contents_flattened_error(): + client = RegistryClient( + 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_artifact_contents( + registry_service.GetArtifactContentsRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_artifact_contents_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_artifact_contents), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = httpbody_pb2.HttpBody() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_artifact_contents( + 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_artifact_contents_flattened_error_async(): + client = RegistryAsyncClient( + 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_artifact_contents( + registry_service.GetArtifactContentsRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateArtifactRequest, + dict, +]) +def test_create_artifact(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + ) + response = client.create_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateArtifactRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +def test_create_artifact_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_artifact), + '__call__') as call: + client.create_artifact() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateArtifactRequest() + +@pytest.mark.asyncio +async def test_create_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateArtifactRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + )) + response = await client.create_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.CreateArtifactRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_create_artifact_async_from_dict(): + await test_create_artifact_async(request_type=dict) + + +def test_create_artifact_field_headers(): + client = RegistryClient( + 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 = registry_service.CreateArtifactRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_artifact), + '__call__') as call: + call.return_value = registry_models.Artifact() + client.create_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_create_artifact_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.CreateArtifactRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_artifact), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) + await client.create_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_create_artifact_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_artifact( + parent='parent_value', + artifact=registry_models.Artifact(name='name_value'), + artifact_id='artifact_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].artifact + mock_val = registry_models.Artifact(name='name_value') + assert arg == mock_val + arg = args[0].artifact_id + mock_val = 'artifact_id_value' + assert arg == mock_val + + +def test_create_artifact_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_artifact( + registry_service.CreateArtifactRequest(), + parent='parent_value', + artifact=registry_models.Artifact(name='name_value'), + artifact_id='artifact_id_value', + ) + +@pytest.mark.asyncio +async def test_create_artifact_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_artifact( + parent='parent_value', + artifact=registry_models.Artifact(name='name_value'), + artifact_id='artifact_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].artifact + mock_val = registry_models.Artifact(name='name_value') + assert arg == mock_val + arg = args[0].artifact_id + mock_val = 'artifact_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_artifact_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_artifact( + registry_service.CreateArtifactRequest(), + parent='parent_value', + artifact=registry_models.Artifact(name='name_value'), + artifact_id='artifact_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ReplaceArtifactRequest, + dict, +]) +def test_replace_artifact(request_type, transport: str = 'grpc'): + client = RegistryClient( + 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.replace_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + ) + response = client.replace_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ReplaceArtifactRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +def test_replace_artifact_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 = RegistryClient( + 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.replace_artifact), + '__call__') as call: + client.replace_artifact() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ReplaceArtifactRequest() + +@pytest.mark.asyncio +async def test_replace_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.ReplaceArtifactRequest): + client = RegistryAsyncClient( + 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.replace_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + )) + response = await client.replace_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.ReplaceArtifactRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +@pytest.mark.asyncio +async def test_replace_artifact_async_from_dict(): + await test_replace_artifact_async(request_type=dict) + + +def test_replace_artifact_field_headers(): + client = RegistryClient( + 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 = registry_service.ReplaceArtifactRequest() + + request.artifact.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_artifact), + '__call__') as call: + call.return_value = registry_models.Artifact() + client.replace_artifact(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', + 'artifact.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_replace_artifact_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.ReplaceArtifactRequest() + + request.artifact.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_artifact), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) + await client.replace_artifact(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', + 'artifact.name=name_value', + ) in kw['metadata'] + + +def test_replace_artifact_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.replace_artifact( + artifact=registry_models.Artifact(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].artifact + mock_val = registry_models.Artifact(name='name_value') + assert arg == mock_val + + +def test_replace_artifact_flattened_error(): + client = RegistryClient( + 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.replace_artifact( + registry_service.ReplaceArtifactRequest(), + artifact=registry_models.Artifact(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_replace_artifact_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.replace_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = registry_models.Artifact() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.replace_artifact( + artifact=registry_models.Artifact(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].artifact + mock_val = registry_models.Artifact(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_replace_artifact_flattened_error_async(): + client = RegistryAsyncClient( + 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.replace_artifact( + registry_service.ReplaceArtifactRequest(), + artifact=registry_models.Artifact(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteArtifactRequest, + dict, +]) +def test_delete_artifact(request_type, transport: str = 'grpc'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteArtifactRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_artifact_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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_artifact), + '__call__') as call: + client.delete_artifact() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteArtifactRequest() + +@pytest.mark.asyncio +async def test_delete_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteArtifactRequest): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == registry_service.DeleteArtifactRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_artifact_async_from_dict(): + await test_delete_artifact_async(request_type=dict) + + +def test_delete_artifact_field_headers(): + client = RegistryClient( + 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 = registry_service.DeleteArtifactRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_artifact), + '__call__') as call: + call.return_value = None + client.delete_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_delete_artifact_field_headers_async(): + client = RegistryAsyncClient( + 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 = registry_service.DeleteArtifactRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_artifact), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_artifact(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_delete_artifact_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_artifact( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_delete_artifact_flattened_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_artifact( + registry_service.DeleteArtifactRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_artifact_flattened_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_artifact), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_artifact( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_delete_artifact_flattened_error_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_artifact( + registry_service.DeleteArtifactRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApisRequest, + dict, +]) +def test_list_apis_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApisResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApisResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_apis(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApisPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_apis_rest_required_fields(request_type=registry_service.ListApisRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_apis._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_apis._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApisResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_service.ListApisResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_apis(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_apis_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_apis._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_apis_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_list_apis") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_list_apis") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ListApisRequest.pb(registry_service.ListApisRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_service.ListApisResponse.to_json(registry_service.ListApisResponse()) + + request = registry_service.ListApisRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_service.ListApisResponse() + + client.list_apis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_apis_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApisRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_apis(request) + + +def test_list_apis_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApisResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApisResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_apis(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/apis" % client.transport._host, args[1]) + + +def test_list_apis_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_apis( + registry_service.ListApisRequest(), + parent='parent_value', + ) + + +def test_list_apis_rest_pager(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + registry_models.Api(), + ], + next_page_token='abc', + ), + registry_service.ListApisResponse( + apis=[], + next_page_token='def', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + ], + next_page_token='ghi', + ), + registry_service.ListApisResponse( + apis=[ + registry_models.Api(), + registry_models.Api(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(registry_service.ListApisResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_apis(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.Api) + for i in results) + + pages = list(client.list_apis(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetApiRequest, + dict, +]) +def test_get_api_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_api(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +def test_get_api_rest_required_fields(request_type=registry_service.GetApiRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.Api() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_api(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_api_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_api._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_api_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_get_api") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.GetApiRequest.pb(registry_service.GetApiRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.Api.to_json(registry_models.Api()) + + request = registry_service.GetApiRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.Api() + + client.get_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_api(request) + + +def test_get_api_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Api() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_api(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*}" % client.transport._host, args[1]) + + +def test_get_api_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_api( + registry_service.GetApiRequest(), + name='name_value', + ) + + +def test_get_api_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiRequest, + dict, +]) +def test_create_api_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["api"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_api(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +def test_create_api_rest_required_fields(request_type=registry_service.CreateApiRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["api_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "apiId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "apiId" in jsonified_request + assert jsonified_request["apiId"] == request_init["api_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["apiId"] = 'api_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("api_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "apiId" in jsonified_request + assert jsonified_request["apiId"] == 'api_id_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.Api() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_api(request) + + expected_params = [ + ( + "apiId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_api_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_api._get_unset_required_fields({}) + assert set(unset_fields) == (set(("apiId", )) & set(("parent", "api", "apiId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_api_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_create_api") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.CreateApiRequest.pb(registry_service.CreateApiRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.Api.to_json(registry_models.Api()) + + request = registry_service.CreateApiRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.Api() + + client.create_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["api"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_api(request) + + +def test_create_api_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Api() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + api=registry_models.Api(name='name_value'), + api_id='api_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_api(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/apis" % client.transport._host, args[1]) + + +def test_create_api_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api( + registry_service.CreateApiRequest(), + parent='parent_value', + api=registry_models.Api(name='name_value'), + api_id='api_id_value', + ) + + +def test_create_api_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiRequest, + dict, +]) +def test_update_api_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'api': {'name': 'projects/sample1/locations/sample2/apis/sample3'}} + request_init["api"] = {'name': 'projects/sample1/locations/sample2/apis/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Api( + name='name_value', + display_name='display_name_value', + description='description_value', + availability='availability_value', + recommended_version='recommended_version_value', + recommended_deployment='recommended_deployment_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_api(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Api) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.availability == 'availability_value' + assert response.recommended_version == 'recommended_version_value' + assert response.recommended_deployment == 'recommended_deployment_value' + + +def test_update_api_rest_required_fields(request_type=registry_service.UpdateApiRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.Api() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_api(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_api_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_api._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("api", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_api_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_update_api") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.UpdateApiRequest.pb(registry_service.UpdateApiRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.Api.to_json(registry_models.Api()) + + request = registry_service.UpdateApiRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.Api() + + client.update_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'api': {'name': 'projects/sample1/locations/sample2/apis/sample3'}} + request_init["api"] = {'name': 'projects/sample1/locations/sample2/apis/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_api(request) + + +def test_update_api_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Api() + + # get arguments that satisfy an http rule for this method + sample_request = {'api': {'name': 'projects/sample1/locations/sample2/apis/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + api=registry_models.Api(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Api.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_api(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{api.name=projects/*/locations/*/apis/*}" % client.transport._host, args[1]) + + +def test_update_api_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api( + registry_service.UpdateApiRequest(), + api=registry_models.Api(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_api_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiRequest, + dict, +]) +def test_delete_api_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_api(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_rest_required_fields(request_type=registry_service.DeleteApiRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_api(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_api_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_api._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api") as pre: + pre.assert_not_called() + pb_message = registry_service.DeleteApiRequest.pb(registry_service.DeleteApiRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = registry_service.DeleteApiRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_api(request) + + +def test_delete_api_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_api(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*}" % client.transport._host, args[1]) + + +def test_delete_api_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api( + registry_service.DeleteApiRequest(), + name='name_value', + ) + + +def test_delete_api_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiVersionsRequest, + dict, +]) +def test_list_api_versions_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiVersionsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_api_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiVersionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_versions_rest_required_fields(request_type=registry_service.ListApiVersionsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_service.ListApiVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_api_versions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_api_versions_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_api_versions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_api_versions_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_versions") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ListApiVersionsRequest.pb(registry_service.ListApiVersionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_service.ListApiVersionsResponse.to_json(registry_service.ListApiVersionsResponse()) + + request = registry_service.ListApiVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_service.ListApiVersionsResponse() + + client.list_api_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_api_versions_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiVersionsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_api_versions(request) + + +def test_list_api_versions_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_api_versions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/versions" % client.transport._host, args[1]) + + +def test_list_api_versions_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_api_versions( + registry_service.ListApiVersionsRequest(), + parent='parent_value', + ) + + +def test_list_api_versions_rest_pager(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + next_page_token='abc', + ), + registry_service.ListApiVersionsResponse( + api_versions=[], + next_page_token='def', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + ], + next_page_token='ghi', + ), + registry_service.ListApiVersionsResponse( + api_versions=[ + registry_models.ApiVersion(), + registry_models.ApiVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(registry_service.ListApiVersionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + + pager = client.list_api_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiVersion) + for i in results) + + pages = list(client.list_api_versions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetApiVersionRequest, + dict, +]) +def test_get_api_version_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_api_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +def test_get_api_version_rest_required_fields(request_type=registry_service.GetApiVersionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_api_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_api_version_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_api_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_api_version_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_version") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.GetApiVersionRequest.pb(registry_service.GetApiVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiVersion.to_json(registry_models.ApiVersion()) + + request = registry_service.GetApiVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiVersion() + + client.get_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiVersionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_api_version(request) + + +def test_get_api_version_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_api_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*}" % client.transport._host, args[1]) + + +def test_get_api_version_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_api_version( + registry_service.GetApiVersionRequest(), + name='name_value', + ) + + +def test_get_api_version_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiVersionRequest, + dict, +]) +def test_create_api_version_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request_init["api_version"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_api_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +def test_create_api_version_rest_required_fields(request_type=registry_service.CreateApiVersionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["api_version_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "apiVersionId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "apiVersionId" in jsonified_request + assert jsonified_request["apiVersionId"] == request_init["api_version_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["apiVersionId"] = 'api_version_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("api_version_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "apiVersionId" in jsonified_request + assert jsonified_request["apiVersionId"] == 'api_version_id_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_api_version(request) + + expected_params = [ + ( + "apiVersionId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_api_version_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_api_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(("apiVersionId", )) & set(("parent", "apiVersion", "apiVersionId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_api_version_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_create_api_version") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.CreateApiVersionRequest.pb(registry_service.CreateApiVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiVersion.to_json(registry_models.ApiVersion()) + + request = registry_service.CreateApiVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiVersion() + + client.create_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiVersionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request_init["api_version"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_api_version(request) + + +def test_create_api_version_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + api_version=registry_models.ApiVersion(name='name_value'), + api_version_id='api_version_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_api_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/versions" % client.transport._host, args[1]) + + +def test_create_api_version_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api_version( + registry_service.CreateApiVersionRequest(), + parent='parent_value', + api_version=registry_models.ApiVersion(name='name_value'), + api_version_id='api_version_id_value', + ) + + +def test_create_api_version_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiVersionRequest, + dict, +]) +def test_update_api_version_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'api_version': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'}} + request_init["api_version"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion( + name='name_value', + display_name='display_name_value', + description='description_value', + state='state_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_api_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiVersion) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.state == 'state_value' + + +def test_update_api_version_rest_required_fields(request_type=registry_service.UpdateApiVersionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_api_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_api_version_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_api_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("apiVersion", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_api_version_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_update_api_version") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.UpdateApiVersionRequest.pb(registry_service.UpdateApiVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiVersion.to_json(registry_models.ApiVersion()) + + request = registry_service.UpdateApiVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiVersion() + + client.update_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiVersionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'api_version': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'}} + request_init["api_version"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_api_version(request) + + +def test_update_api_version_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'api_version': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + api_version=registry_models.ApiVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiVersion.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_api_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{api_version.name=projects/*/locations/*/apis/*/versions/*}" % client.transport._host, args[1]) + + +def test_update_api_version_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api_version( + registry_service.UpdateApiVersionRequest(), + api_version=registry_models.ApiVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_api_version_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiVersionRequest, + dict, +]) +def test_delete_api_version_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_api_version(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_version_rest_required_fields(request_type=registry_service.DeleteApiVersionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_api_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_api_version_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_api_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_version_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_version") as pre: + pre.assert_not_called() + pb_message = registry_service.DeleteApiVersionRequest.pb(registry_service.DeleteApiVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = registry_service.DeleteApiVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiVersionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_api_version(request) + + +def test_delete_api_version_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_api_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*}" % client.transport._host, args[1]) + + +def test_delete_api_version_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_version( + registry_service.DeleteApiVersionRequest(), + name='name_value', + ) + + +def test_delete_api_version_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiSpecsRequest, + dict, +]) +def test_list_api_specs_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiSpecsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiSpecsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_api_specs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiSpecsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_specs_rest_required_fields(request_type=registry_service.ListApiSpecsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_specs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_specs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiSpecsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_service.ListApiSpecsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_api_specs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_api_specs_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_api_specs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_api_specs_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_specs") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_specs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ListApiSpecsRequest.pb(registry_service.ListApiSpecsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_service.ListApiSpecsResponse.to_json(registry_service.ListApiSpecsResponse()) + + request = registry_service.ListApiSpecsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_service.ListApiSpecsResponse() + + client.list_api_specs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_api_specs_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiSpecsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_api_specs(request) + + +def test_list_api_specs_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiSpecsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiSpecsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_api_specs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs" % client.transport._host, args[1]) + + +def test_list_api_specs_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_api_specs( + registry_service.ListApiSpecsRequest(), + parent='parent_value', + ) + + +def test_list_api_specs_rest_pager(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(registry_service.ListApiSpecsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + + pager = client.list_api_specs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiSpec) + for i in results) + + pages = list(client.list_api_specs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetApiSpecRequest, + dict, +]) +def test_get_api_spec_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_api_spec(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_get_api_spec_rest_required_fields(request_type=registry_service.GetApiSpecRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_api_spec(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_api_spec_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_api_spec._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_api_spec_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_spec") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_spec") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.GetApiSpecRequest.pb(registry_service.GetApiSpecRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) + + request = registry_service.GetApiSpecRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiSpec() + + client.get_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiSpecRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_api_spec(request) + + +def test_get_api_spec_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_api_spec(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}" % client.transport._host, args[1]) + + +def test_get_api_spec_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_api_spec( + registry_service.GetApiSpecRequest(), + name='name_value', + ) + + +def test_get_api_spec_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetApiSpecContentsRequest, + dict, +]) +def test_get_api_spec_contents_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_api_spec_contents(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_get_api_spec_contents_rest_required_fields(request_type=registry_service.GetApiSpecContentsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec_contents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec_contents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_api_spec_contents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_api_spec_contents_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_api_spec_contents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_api_spec_contents_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_spec_contents") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_spec_contents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.GetApiSpecContentsRequest.pb(registry_service.GetApiSpecContentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) + + request = registry_service.GetApiSpecContentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.get_api_spec_contents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_api_spec_contents_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiSpecContentsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_api_spec_contents(request) + + +def test_get_api_spec_contents_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_api_spec_contents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:getContents" % client.transport._host, args[1]) + + +def test_get_api_spec_contents_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_api_spec_contents( + registry_service.GetApiSpecContentsRequest(), + name='name_value', + ) + + +def test_get_api_spec_contents_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiSpecRequest, + dict, +]) +def test_create_api_spec_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request_init["api_spec"] = {'name': 'name_value', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_api_spec(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_create_api_spec_rest_required_fields(request_type=registry_service.CreateApiSpecRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["api_spec_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "apiSpecId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_spec._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "apiSpecId" in jsonified_request + assert jsonified_request["apiSpecId"] == request_init["api_spec_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["apiSpecId"] = 'api_spec_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_spec._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("api_spec_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "apiSpecId" in jsonified_request + assert jsonified_request["apiSpecId"] == 'api_spec_id_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_api_spec(request) + + expected_params = [ + ( + "apiSpecId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_api_spec_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_api_spec._get_unset_required_fields({}) + assert set(unset_fields) == (set(("apiSpecId", )) & set(("parent", "apiSpec", "apiSpecId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_api_spec_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_create_api_spec") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api_spec") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.CreateApiSpecRequest.pb(registry_service.CreateApiSpecRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) + + request = registry_service.CreateApiSpecRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiSpec() + + client.create_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiSpecRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + request_init["api_spec"] = {'name': 'name_value', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_api_spec(request) + + +def test_create_api_spec_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + api_spec=registry_models.ApiSpec(name='name_value'), + api_spec_id='api_spec_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_api_spec(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs" % client.transport._host, args[1]) + + +def test_create_api_spec_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api_spec( + registry_service.CreateApiSpecRequest(), + parent='parent_value', + api_spec=registry_models.ApiSpec(name='name_value'), + api_spec_id='api_spec_id_value', + ) + + +def test_create_api_spec_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiSpecRequest, + dict, +]) +def test_update_api_spec_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'api_spec': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'}} + request_init["api_spec"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_api_spec(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_update_api_spec_rest_required_fields(request_type=registry_service.UpdateApiSpecRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_spec._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_spec._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_api_spec(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_api_spec_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_api_spec._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("apiSpec", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_api_spec_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_update_api_spec") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api_spec") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.UpdateApiSpecRequest.pb(registry_service.UpdateApiSpecRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) + + request = registry_service.UpdateApiSpecRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiSpec() + + client.update_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiSpecRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'api_spec': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'}} + request_init["api_spec"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_api_spec(request) + + +def test_update_api_spec_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + + # get arguments that satisfy an http rule for this method + sample_request = {'api_spec': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + api_spec=registry_models.ApiSpec(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_api_spec(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{api_spec.name=projects/*/locations/*/apis/*/versions/*/specs/*}" % client.transport._host, args[1]) + + +def test_update_api_spec_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api_spec( + registry_service.UpdateApiSpecRequest(), + api_spec=registry_models.ApiSpec(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_api_spec_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiSpecRequest, + dict, +]) +def test_delete_api_spec_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_api_spec(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_spec_rest_required_fields(request_type=registry_service.DeleteApiSpecRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_api_spec(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_api_spec_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_api_spec._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_spec_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_spec") as pre: + pre.assert_not_called() + pb_message = registry_service.DeleteApiSpecRequest.pb(registry_service.DeleteApiSpecRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = registry_service.DeleteApiSpecRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiSpecRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_api_spec(request) + + +def test_delete_api_spec_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_api_spec(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}" % client.transport._host, args[1]) + + +def test_delete_api_spec_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_spec( + registry_service.DeleteApiSpecRequest(), + name='name_value', + ) + + +def test_delete_api_spec_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.TagApiSpecRevisionRequest, + dict, +]) +def test_tag_api_spec_revision_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.tag_api_spec_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_tag_api_spec_revision_rest_required_fields(request_type=registry_service.TagApiSpecRevisionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request_init["tag"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_spec_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["tag"] = 'tag_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_spec_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "tag" in jsonified_request + assert jsonified_request["tag"] == 'tag_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.tag_api_spec_revision(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_tag_api_spec_revision_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.tag_api_spec_revision._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "tag", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_tag_api_spec_revision_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_tag_api_spec_revision") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_tag_api_spec_revision") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.TagApiSpecRevisionRequest.pb(registry_service.TagApiSpecRevisionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) + + request = registry_service.TagApiSpecRevisionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiSpec() + + client.tag_api_spec_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_tag_api_spec_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.TagApiSpecRevisionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.tag_api_spec_revision(request) + + +def test_tag_api_spec_revision_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiSpecRevisionsRequest, + dict, +]) +def test_list_api_spec_revisions_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiSpecRevisionsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiSpecRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_api_spec_revisions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiSpecRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_spec_revisions_rest_required_fields(request_type=registry_service.ListApiSpecRevisionsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_spec_revisions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_spec_revisions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiSpecRevisionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_service.ListApiSpecRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_api_spec_revisions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_api_spec_revisions_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_api_spec_revisions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_api_spec_revisions_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_spec_revisions") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_spec_revisions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ListApiSpecRevisionsRequest.pb(registry_service.ListApiSpecRevisionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_service.ListApiSpecRevisionsResponse.to_json(registry_service.ListApiSpecRevisionsResponse()) + + request = registry_service.ListApiSpecRevisionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_service.ListApiSpecRevisionsResponse() + + client.list_api_spec_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_api_spec_revisions_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiSpecRevisionsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_api_spec_revisions(request) + + +def test_list_api_spec_revisions_rest_pager(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + next_page_token='abc', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[], + next_page_token='def', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + ], + next_page_token='ghi', + ), + registry_service.ListApiSpecRevisionsResponse( + api_specs=[ + registry_models.ApiSpec(), + registry_models.ApiSpec(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(registry_service.ListApiSpecRevisionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + + pager = client.list_api_spec_revisions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiSpec) + for i in results) + + pages = list(client.list_api_spec_revisions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + registry_service.RollbackApiSpecRequest, + dict, +]) +def test_rollback_api_spec_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.rollback_api_spec(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_rollback_api_spec_rest_required_fields(request_type=registry_service.RollbackApiSpecRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request_init["revision_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_spec._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["revisionId"] = 'revision_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_spec._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "revisionId" in jsonified_request + assert jsonified_request["revisionId"] == 'revision_id_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.rollback_api_spec(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_rollback_api_spec_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.rollback_api_spec._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "revisionId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_rollback_api_spec_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_rollback_api_spec") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_rollback_api_spec") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.RollbackApiSpecRequest.pb(registry_service.RollbackApiSpecRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) + + request = registry_service.RollbackApiSpecRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiSpec() + + client.rollback_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rollback_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.RollbackApiSpecRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.rollback_api_spec(request) + + +def test_rollback_api_spec_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiSpecRevisionRequest, + dict, +]) +def test_delete_api_spec_revision_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec( + name='name_value', + filename='filename_value', + description='description_value', + revision_id='revision_id_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + source_uri='source_uri_value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_api_spec_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiSpec) + assert response.name == 'name_value' + assert response.filename == 'filename_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.source_uri == 'source_uri_value' + assert response.contents == b'contents_blob' + + +def test_delete_api_spec_revision_rest_required_fields(request_type=registry_service.DeleteApiSpecRevisionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_api_spec_revision(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_api_spec_revision_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_api_spec_revision._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_spec_revision_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_delete_api_spec_revision") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_spec_revision") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.DeleteApiSpecRevisionRequest.pb(registry_service.DeleteApiSpecRevisionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) + + request = registry_service.DeleteApiSpecRevisionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiSpec() + + client.delete_api_spec_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_api_spec_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiSpecRevisionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_api_spec_revision(request) + + +def test_delete_api_spec_revision_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiSpec() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiSpec.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_api_spec_revision(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:deleteRevision" % client.transport._host, args[1]) + + +def test_delete_api_spec_revision_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_spec_revision( + registry_service.DeleteApiSpecRevisionRequest(), + name='name_value', + ) + + +def test_delete_api_spec_revision_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiDeploymentsRequest, + dict, +]) +def test_list_api_deployments_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiDeploymentsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_api_deployments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiDeploymentsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_deployments_rest_required_fields(request_type=registry_service.ListApiDeploymentsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployments._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiDeploymentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_service.ListApiDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_api_deployments(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_api_deployments_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_api_deployments._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_api_deployments_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_deployments") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_deployments") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ListApiDeploymentsRequest.pb(registry_service.ListApiDeploymentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_service.ListApiDeploymentsResponse.to_json(registry_service.ListApiDeploymentsResponse()) + + request = registry_service.ListApiDeploymentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_service.ListApiDeploymentsResponse() + + client.list_api_deployments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_api_deployments_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiDeploymentsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_api_deployments(request) + + +def test_list_api_deployments_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiDeploymentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_api_deployments(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/deployments" % client.transport._host, args[1]) + + +def test_list_api_deployments_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_api_deployments( + registry_service.ListApiDeploymentsRequest(), + parent='parent_value', + ) + + +def test_list_api_deployments_rest_pager(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(registry_service.ListApiDeploymentsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + + pager = client.list_api_deployments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiDeployment) + for i in results) + + pages = list(client.list_api_deployments(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetApiDeploymentRequest, + dict, +]) +def test_get_api_deployment_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_api_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_get_api_deployment_rest_required_fields(request_type=registry_service.GetApiDeploymentRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_api_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_api_deployment_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_api_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_api_deployment_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_deployment") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.GetApiDeploymentRequest.pb(registry_service.GetApiDeploymentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) + + request = registry_service.GetApiDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiDeployment() + + client.get_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiDeploymentRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_api_deployment(request) + + +def test_get_api_deployment_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_api_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/deployments/*}" % client.transport._host, args[1]) + + +def test_get_api_deployment_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_api_deployment( + registry_service.GetApiDeploymentRequest(), + name='name_value', + ) + + +def test_get_api_deployment_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateApiDeploymentRequest, + dict, +]) +def test_create_api_deployment_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request_init["api_deployment"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_api_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_create_api_deployment_rest_required_fields(request_type=registry_service.CreateApiDeploymentRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["api_deployment_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "apiDeploymentId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "apiDeploymentId" in jsonified_request + assert jsonified_request["apiDeploymentId"] == request_init["api_deployment_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["apiDeploymentId"] = 'api_deployment_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("api_deployment_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "apiDeploymentId" in jsonified_request + assert jsonified_request["apiDeploymentId"] == 'api_deployment_id_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_api_deployment(request) + + expected_params = [ + ( + "apiDeploymentId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_api_deployment_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_api_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("apiDeploymentId", )) & set(("parent", "apiDeployment", "apiDeploymentId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_api_deployment_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_create_api_deployment") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.CreateApiDeploymentRequest.pb(registry_service.CreateApiDeploymentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) + + request = registry_service.CreateApiDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiDeployment() + + client.create_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiDeploymentRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + request_init["api_deployment"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_api_deployment(request) + + +def test_create_api_deployment_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + api_deployment=registry_models.ApiDeployment(name='name_value'), + api_deployment_id='api_deployment_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_api_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/deployments" % client.transport._host, args[1]) + + +def test_create_api_deployment_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_api_deployment( + registry_service.CreateApiDeploymentRequest(), + parent='parent_value', + api_deployment=registry_models.ApiDeployment(name='name_value'), + api_deployment_id='api_deployment_id_value', + ) + + +def test_create_api_deployment_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.UpdateApiDeploymentRequest, + dict, +]) +def test_update_api_deployment_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'api_deployment': {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'}} + request_init["api_deployment"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_api_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_update_api_deployment_rest_required_fields(request_type=registry_service.UpdateApiDeploymentRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("allow_missing", "update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "patch", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_api_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_api_deployment_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_api_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("apiDeployment", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_api_deployment_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_update_api_deployment") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.UpdateApiDeploymentRequest.pb(registry_service.UpdateApiDeploymentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) + + request = registry_service.UpdateApiDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiDeployment() + + client.update_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiDeploymentRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'api_deployment': {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'}} + request_init["api_deployment"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_api_deployment(request) + + +def test_update_api_deployment_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + + # get arguments that satisfy an http rule for this method + sample_request = {'api_deployment': {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + api_deployment=registry_models.ApiDeployment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_api_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{api_deployment.name=projects/*/locations/*/apis/*/deployments/*}" % client.transport._host, args[1]) + + +def test_update_api_deployment_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_api_deployment( + registry_service.UpdateApiDeploymentRequest(), + api_deployment=registry_models.ApiDeployment(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_api_deployment_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiDeploymentRequest, + dict, +]) +def test_delete_api_deployment_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_api_deployment(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_api_deployment_rest_required_fields(request_type=registry_service.DeleteApiDeploymentRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_api_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_api_deployment_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_api_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_deployment_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_deployment") as pre: + pre.assert_not_called() + pb_message = registry_service.DeleteApiDeploymentRequest.pb(registry_service.DeleteApiDeploymentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = registry_service.DeleteApiDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiDeploymentRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_api_deployment(request) + + +def test_delete_api_deployment_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_api_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/deployments/*}" % client.transport._host, args[1]) + + +def test_delete_api_deployment_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_deployment( + registry_service.DeleteApiDeploymentRequest(), + name='name_value', + ) + + +def test_delete_api_deployment_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.TagApiDeploymentRevisionRequest, + dict, +]) +def test_tag_api_deployment_revision_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.tag_api_deployment_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_tag_api_deployment_revision_rest_required_fields(request_type=registry_service.TagApiDeploymentRevisionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request_init["tag"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_deployment_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["tag"] = 'tag_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_deployment_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "tag" in jsonified_request + assert jsonified_request["tag"] == 'tag_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.tag_api_deployment_revision(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_tag_api_deployment_revision_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.tag_api_deployment_revision._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "tag", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_tag_api_deployment_revision_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_tag_api_deployment_revision") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_tag_api_deployment_revision") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.TagApiDeploymentRevisionRequest.pb(registry_service.TagApiDeploymentRevisionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) + + request = registry_service.TagApiDeploymentRevisionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiDeployment() + + client.tag_api_deployment_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_tag_api_deployment_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.TagApiDeploymentRevisionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.tag_api_deployment_revision(request) + + +def test_tag_api_deployment_revision_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListApiDeploymentRevisionsRequest, + dict, +]) +def test_list_api_deployment_revisions_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiDeploymentRevisionsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListApiDeploymentRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_api_deployment_revisions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListApiDeploymentRevisionsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_api_deployment_revisions_rest_required_fields(request_type=registry_service.ListApiDeploymentRevisionsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployment_revisions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployment_revisions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_service.ListApiDeploymentRevisionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_service.ListApiDeploymentRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_api_deployment_revisions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_api_deployment_revisions_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_api_deployment_revisions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_api_deployment_revisions_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_deployment_revisions") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_deployment_revisions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ListApiDeploymentRevisionsRequest.pb(registry_service.ListApiDeploymentRevisionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_service.ListApiDeploymentRevisionsResponse.to_json(registry_service.ListApiDeploymentRevisionsResponse()) + + request = registry_service.ListApiDeploymentRevisionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_service.ListApiDeploymentRevisionsResponse() + + client.list_api_deployment_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_api_deployment_revisions_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiDeploymentRevisionsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_api_deployment_revisions(request) + + +def test_list_api_deployment_revisions_rest_pager(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + next_page_token='abc', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[], + next_page_token='def', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + ], + next_page_token='ghi', + ), + registry_service.ListApiDeploymentRevisionsResponse( + api_deployments=[ + registry_models.ApiDeployment(), + registry_models.ApiDeployment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(registry_service.ListApiDeploymentRevisionsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + + pager = client.list_api_deployment_revisions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.ApiDeployment) + for i in results) + + pages = list(client.list_api_deployment_revisions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + registry_service.RollbackApiDeploymentRequest, + dict, +]) +def test_rollback_api_deployment_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.rollback_api_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_rollback_api_deployment_rest_required_fields(request_type=registry_service.RollbackApiDeploymentRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request_init["revision_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["revisionId"] = 'revision_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "revisionId" in jsonified_request + assert jsonified_request["revisionId"] == 'revision_id_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.rollback_api_deployment(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_rollback_api_deployment_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.rollback_api_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "revisionId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_rollback_api_deployment_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_rollback_api_deployment") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_rollback_api_deployment") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.RollbackApiDeploymentRequest.pb(registry_service.RollbackApiDeploymentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) + + request = registry_service.RollbackApiDeploymentRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiDeployment() + + client.rollback_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_rollback_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.RollbackApiDeploymentRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.rollback_api_deployment(request) + + +def test_rollback_api_deployment_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteApiDeploymentRevisionRequest, + dict, +]) +def test_delete_api_deployment_revision_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment( + name='name_value', + display_name='display_name_value', + description='description_value', + revision_id='revision_id_value', + api_spec_revision='api_spec_revision_value', + endpoint_uri='endpoint_uri_value', + external_channel_uri='external_channel_uri_value', + intended_audience='intended_audience_value', + access_guidance='access_guidance_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_api_deployment_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.ApiDeployment) + assert response.name == 'name_value' + assert response.display_name == 'display_name_value' + assert response.description == 'description_value' + assert response.revision_id == 'revision_id_value' + assert response.api_spec_revision == 'api_spec_revision_value' + assert response.endpoint_uri == 'endpoint_uri_value' + assert response.external_channel_uri == 'external_channel_uri_value' + assert response.intended_audience == 'intended_audience_value' + assert response.access_guidance == 'access_guidance_value' + + +def test_delete_api_deployment_revision_rest_required_fields(request_type=registry_service.DeleteApiDeploymentRevisionRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment_revision._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_api_deployment_revision(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_api_deployment_revision_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_api_deployment_revision._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_api_deployment_revision_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_delete_api_deployment_revision") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_deployment_revision") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.DeleteApiDeploymentRevisionRequest.pb(registry_service.DeleteApiDeploymentRevisionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) + + request = registry_service.DeleteApiDeploymentRevisionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.ApiDeployment() + + client.delete_api_deployment_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_api_deployment_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiDeploymentRevisionRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_api_deployment_revision(request) + + +def test_delete_api_deployment_revision_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.ApiDeployment() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.ApiDeployment.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_api_deployment_revision(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/deployments/*}:deleteRevision" % client.transport._host, args[1]) + + +def test_delete_api_deployment_revision_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_api_deployment_revision( + registry_service.DeleteApiDeploymentRevisionRequest(), + name='name_value', + ) + + +def test_delete_api_deployment_revision_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ListArtifactsRequest, + dict, +]) +def test_list_artifacts_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListArtifactsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListArtifactsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_artifacts(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListArtifactsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_artifacts_rest_required_fields(request_type=registry_service.ListArtifactsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_artifacts._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_artifacts._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_service.ListArtifactsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_service.ListArtifactsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_artifacts(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_artifacts_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_artifacts._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_artifacts_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_list_artifacts") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_list_artifacts") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ListArtifactsRequest.pb(registry_service.ListArtifactsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_service.ListArtifactsResponse.to_json(registry_service.ListArtifactsResponse()) + + request = registry_service.ListArtifactsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_service.ListArtifactsResponse() + + client.list_artifacts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_artifacts_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListArtifactsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_artifacts(request) + + +def test_list_artifacts_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_service.ListArtifactsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_service.ListArtifactsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_artifacts(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/artifacts" % client.transport._host, args[1]) + + +def test_list_artifacts_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_artifacts( + registry_service.ListArtifactsRequest(), + parent='parent_value', + ) + + +def test_list_artifacts_rest_pager(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + registry_models.Artifact(), + ], + next_page_token='abc', + ), + registry_service.ListArtifactsResponse( + artifacts=[], + next_page_token='def', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + ], + next_page_token='ghi', + ), + registry_service.ListArtifactsResponse( + artifacts=[ + registry_models.Artifact(), + registry_models.Artifact(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(registry_service.ListArtifactsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode('UTF-8') + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + pager = client.list_artifacts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, registry_models.Artifact) + for i in results) + + pages = list(client.list_artifacts(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetArtifactRequest, + dict, +]) +def test_get_artifact_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_artifact(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +def test_get_artifact_rest_required_fields(request_type=registry_service.GetArtifactRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_artifact(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_artifact_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_artifact._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_artifact_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_get_artifact") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_get_artifact") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.GetArtifactRequest.pb(registry_service.GetArtifactRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.Artifact.to_json(registry_models.Artifact()) + + request = registry_service.GetArtifactRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.Artifact() + + client.get_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetArtifactRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_artifact(request) + + +def test_get_artifact_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_artifact(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/artifacts/*}" % client.transport._host, args[1]) + + +def test_get_artifact_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_artifact( + registry_service.GetArtifactRequest(), + name='name_value', + ) + + +def test_get_artifact_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.GetArtifactContentsRequest, + dict, +]) +def test_get_artifact_contents_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody( + content_type='content_type_value', + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_artifact_contents(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, httpbody_pb2.HttpBody) + assert response.content_type == 'content_type_value' + assert response.data == b'data_blob' + + +def test_get_artifact_contents_rest_required_fields(request_type=registry_service.GetArtifactContentsRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact_contents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact_contents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_artifact_contents(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_artifact_contents_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_artifact_contents._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_artifact_contents_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_get_artifact_contents") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_get_artifact_contents") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.GetArtifactContentsRequest.pb(registry_service.GetArtifactContentsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) + + request = registry_service.GetArtifactContentsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = httpbody_pb2.HttpBody() + + client.get_artifact_contents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_artifact_contents_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetArtifactContentsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_artifact_contents(request) + + +def test_get_artifact_contents_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = httpbody_pb2.HttpBody() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_artifact_contents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/artifacts/*}:getContents" % client.transport._host, args[1]) + + +def test_get_artifact_contents_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_artifact_contents( + registry_service.GetArtifactContentsRequest(), + name='name_value', + ) + + +def test_get_artifact_contents_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.CreateArtifactRequest, + dict, +]) +def test_create_artifact_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["artifact"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_artifact(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +def test_create_artifact_rest_required_fields(request_type=registry_service.CreateArtifactRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["artifact_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "artifactId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_artifact._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "artifactId" in jsonified_request + assert jsonified_request["artifactId"] == request_init["artifact_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["artifactId"] = 'artifact_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_artifact._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("artifact_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "artifactId" in jsonified_request + assert jsonified_request["artifactId"] == 'artifact_id_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_artifact(request) + + expected_params = [ + ( + "artifactId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_artifact_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_artifact._get_unset_required_fields({}) + assert set(unset_fields) == (set(("artifactId", )) & set(("parent", "artifact", "artifactId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_artifact_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_create_artifact") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_create_artifact") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.CreateArtifactRequest.pb(registry_service.CreateArtifactRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.Artifact.to_json(registry_models.Artifact()) + + request = registry_service.CreateArtifactRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.Artifact() + + client.create_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateArtifactRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["artifact"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_artifact(request) + + +def test_create_artifact_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + artifact=registry_models.Artifact(name='name_value'), + artifact_id='artifact_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_artifact(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/artifacts" % client.transport._host, args[1]) + + +def test_create_artifact_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_artifact( + registry_service.CreateArtifactRequest(), + parent='parent_value', + artifact=registry_models.Artifact(name='name_value'), + artifact_id='artifact_id_value', + ) + + +def test_create_artifact_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.ReplaceArtifactRequest, + dict, +]) +def test_replace_artifact_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'artifact': {'name': 'projects/sample1/locations/sample2/artifacts/sample3'}} + request_init["artifact"] = {'name': 'projects/sample1/locations/sample2/artifacts/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact( + name='name_value', + mime_type='mime_type_value', + size_bytes=1089, + hash_='hash__value', + contents=b'contents_blob', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.replace_artifact(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, registry_models.Artifact) + assert response.name == 'name_value' + assert response.mime_type == 'mime_type_value' + assert response.size_bytes == 1089 + assert response.hash_ == 'hash__value' + assert response.contents == b'contents_blob' + + +def test_replace_artifact_rest_required_fields(request_type=registry_service.ReplaceArtifactRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).replace_artifact._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).replace_artifact._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "put", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.replace_artifact(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_replace_artifact_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.replace_artifact._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("artifact", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_replace_artifact_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "post_replace_artifact") as post, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_replace_artifact") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = registry_service.ReplaceArtifactRequest.pb(registry_service.ReplaceArtifactRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = registry_models.Artifact.to_json(registry_models.Artifact()) + + request = registry_service.ReplaceArtifactRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = registry_models.Artifact() + + client.replace_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_replace_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.ReplaceArtifactRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'artifact': {'name': 'projects/sample1/locations/sample2/artifacts/sample3'}} + request_init["artifact"] = {'name': 'projects/sample1/locations/sample2/artifacts/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.replace_artifact(request) + + +def test_replace_artifact_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = registry_models.Artifact() + + # get arguments that satisfy an http rule for this method + sample_request = {'artifact': {'name': 'projects/sample1/locations/sample2/artifacts/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + artifact=registry_models.Artifact(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = registry_models.Artifact.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.replace_artifact(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{artifact.name=projects/*/locations/*/artifacts/*}" % client.transport._host, args[1]) + + +def test_replace_artifact_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.replace_artifact( + registry_service.ReplaceArtifactRequest(), + artifact=registry_models.Artifact(name='name_value'), + ) + + +def test_replace_artifact_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + registry_service.DeleteArtifactRequest, + dict, +]) +def test_delete_artifact_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.delete_artifact(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_artifact_rest_required_fields(request_type=registry_service.DeleteArtifactRequest): + transport_class = transports.RegistryRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_artifact._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_artifact._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "delete", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_artifact(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_artifact_rest_unset_required_fields(): + transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_artifact._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_artifact_rest_interceptors(null_interceptor): + transport = transports.RegistryRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), + ) + client = RegistryClient(transport=transport) + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_artifact") as pre: + pre.assert_not_called() + pb_message = registry_service.DeleteArtifactRequest.pb(registry_service.DeleteArtifactRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = registry_service.DeleteArtifactRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteArtifactRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_artifact(request) + + +def test_delete_artifact_rest_flattened(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '' + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.delete_artifact(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/artifacts/*}" % client.transport._host, args[1]) + + +def test_delete_artifact_rest_flattened_error(transport: str = 'rest'): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_artifact( + registry_service.DeleteArtifactRequest(), + name='name_value', + ) + + +def test_delete_artifact_rest_error(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistryClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegistryClient( + 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 = RegistryClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistryClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegistryClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistryGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegistryGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.RegistryGrpcTransport, + transports.RegistryGrpcAsyncIOTransport, + transports.RegistryRestTransport, +]) +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", + "rest", +]) +def test_transport_kind(transport_name): + transport = RegistryClient.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 = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RegistryGrpcTransport, + ) + +def test_registry_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegistryTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_registry_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.apigee_registry_v1.services.registry.transports.RegistryTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.RegistryTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_apis', + 'get_api', + 'create_api', + 'update_api', + 'delete_api', + 'list_api_versions', + 'get_api_version', + 'create_api_version', + 'update_api_version', + 'delete_api_version', + 'list_api_specs', + 'get_api_spec', + 'get_api_spec_contents', + 'create_api_spec', + 'update_api_spec', + 'delete_api_spec', + 'tag_api_spec_revision', + 'list_api_spec_revisions', + 'rollback_api_spec', + 'delete_api_spec_revision', + 'list_api_deployments', + 'get_api_deployment', + 'create_api_deployment', + 'update_api_deployment', + 'delete_api_deployment', + 'tag_api_deployment_revision', + 'list_api_deployment_revisions', + 'rollback_api_deployment', + 'delete_api_deployment_revision', + 'list_artifacts', + 'get_artifact', + 'get_artifact_contents', + 'create_artifact', + 'replace_artifact', + 'delete_artifact', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + '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() + + # Catch all for all remaining methods and properties + remainder = [ + 'kind', + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_registry_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.apigee_registry_v1.services.registry.transports.RegistryTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistryTransport( + 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_registry_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.apigee_registry_v1.services.registry.transports.RegistryTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegistryTransport() + adc.assert_called_once() + + +def test_registry_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) + RegistryClient() + 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.RegistryGrpcTransport, + transports.RegistryGrpcAsyncIOTransport, + ], +) +def test_registry_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.RegistryGrpcTransport, + transports.RegistryGrpcAsyncIOTransport, + transports.RegistryRestTransport, + ], +) +def test_registry_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.RegistryGrpcTransport, grpc_helpers), + (transports.RegistryGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_registry_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( + "apigeeregistry.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="apigeeregistry.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.RegistryGrpcTransport, transports.RegistryGrpcAsyncIOTransport]) +def test_registry_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 + ) + +def test_registry_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.RegistryRestTransport ( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_registry_host_no_port(transport_name): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://apigeeregistry.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_registry_host_with_port(transport_name): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'apigeeregistry.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://apigeeregistry.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_registry_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegistryClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegistryClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_apis._session + session2 = client2.transport.list_apis._session + assert session1 != session2 + session1 = client1.transport.get_api._session + session2 = client2.transport.get_api._session + assert session1 != session2 + session1 = client1.transport.create_api._session + session2 = client2.transport.create_api._session + assert session1 != session2 + session1 = client1.transport.update_api._session + session2 = client2.transport.update_api._session + assert session1 != session2 + session1 = client1.transport.delete_api._session + session2 = client2.transport.delete_api._session + assert session1 != session2 + session1 = client1.transport.list_api_versions._session + session2 = client2.transport.list_api_versions._session + assert session1 != session2 + session1 = client1.transport.get_api_version._session + session2 = client2.transport.get_api_version._session + assert session1 != session2 + session1 = client1.transport.create_api_version._session + session2 = client2.transport.create_api_version._session + assert session1 != session2 + session1 = client1.transport.update_api_version._session + session2 = client2.transport.update_api_version._session + assert session1 != session2 + session1 = client1.transport.delete_api_version._session + session2 = client2.transport.delete_api_version._session + assert session1 != session2 + session1 = client1.transport.list_api_specs._session + session2 = client2.transport.list_api_specs._session + assert session1 != session2 + session1 = client1.transport.get_api_spec._session + session2 = client2.transport.get_api_spec._session + assert session1 != session2 + session1 = client1.transport.get_api_spec_contents._session + session2 = client2.transport.get_api_spec_contents._session + assert session1 != session2 + session1 = client1.transport.create_api_spec._session + session2 = client2.transport.create_api_spec._session + assert session1 != session2 + session1 = client1.transport.update_api_spec._session + session2 = client2.transport.update_api_spec._session + assert session1 != session2 + session1 = client1.transport.delete_api_spec._session + session2 = client2.transport.delete_api_spec._session + assert session1 != session2 + session1 = client1.transport.tag_api_spec_revision._session + session2 = client2.transport.tag_api_spec_revision._session + assert session1 != session2 + session1 = client1.transport.list_api_spec_revisions._session + session2 = client2.transport.list_api_spec_revisions._session + assert session1 != session2 + session1 = client1.transport.rollback_api_spec._session + session2 = client2.transport.rollback_api_spec._session + assert session1 != session2 + session1 = client1.transport.delete_api_spec_revision._session + session2 = client2.transport.delete_api_spec_revision._session + assert session1 != session2 + session1 = client1.transport.list_api_deployments._session + session2 = client2.transport.list_api_deployments._session + assert session1 != session2 + session1 = client1.transport.get_api_deployment._session + session2 = client2.transport.get_api_deployment._session + assert session1 != session2 + session1 = client1.transport.create_api_deployment._session + session2 = client2.transport.create_api_deployment._session + assert session1 != session2 + session1 = client1.transport.update_api_deployment._session + session2 = client2.transport.update_api_deployment._session + assert session1 != session2 + session1 = client1.transport.delete_api_deployment._session + session2 = client2.transport.delete_api_deployment._session + assert session1 != session2 + session1 = client1.transport.tag_api_deployment_revision._session + session2 = client2.transport.tag_api_deployment_revision._session + assert session1 != session2 + session1 = client1.transport.list_api_deployment_revisions._session + session2 = client2.transport.list_api_deployment_revisions._session + assert session1 != session2 + session1 = client1.transport.rollback_api_deployment._session + session2 = client2.transport.rollback_api_deployment._session + assert session1 != session2 + session1 = client1.transport.delete_api_deployment_revision._session + session2 = client2.transport.delete_api_deployment_revision._session + assert session1 != session2 + session1 = client1.transport.list_artifacts._session + session2 = client2.transport.list_artifacts._session + assert session1 != session2 + session1 = client1.transport.get_artifact._session + session2 = client2.transport.get_artifact._session + assert session1 != session2 + session1 = client1.transport.get_artifact_contents._session + session2 = client2.transport.get_artifact_contents._session + assert session1 != session2 + session1 = client1.transport.create_artifact._session + session2 = client2.transport.create_artifact._session + assert session1 != session2 + session1 = client1.transport.replace_artifact._session + session2 = client2.transport.replace_artifact._session + assert session1 != session2 + session1 = client1.transport.delete_artifact._session + session2 = client2.transport.delete_artifact._session + assert session1 != session2 +def test_registry_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegistryGrpcTransport( + 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_registry_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RegistryGrpcAsyncIOTransport( + 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.RegistryGrpcTransport, transports.RegistryGrpcAsyncIOTransport]) +def test_registry_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.RegistryGrpcTransport, transports.RegistryGrpcAsyncIOTransport]) +def test_registry_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_api_path(): + project = "squid" + location = "clam" + api = "whelk" + expected = "projects/{project}/locations/{location}/apis/{api}".format(project=project, location=location, api=api, ) + actual = RegistryClient.api_path(project, location, api) + assert expected == actual + + +def test_parse_api_path(): + expected = { + "project": "octopus", + "location": "oyster", + "api": "nudibranch", + } + path = RegistryClient.api_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_api_path(path) + assert expected == actual + +def test_api_deployment_path(): + project = "cuttlefish" + location = "mussel" + api = "winkle" + deployment = "nautilus" + expected = "projects/{project}/locations/{location}/apis/{api}/deployments/{deployment}".format(project=project, location=location, api=api, deployment=deployment, ) + actual = RegistryClient.api_deployment_path(project, location, api, deployment) + assert expected == actual + + +def test_parse_api_deployment_path(): + expected = { + "project": "scallop", + "location": "abalone", + "api": "squid", + "deployment": "clam", + } + path = RegistryClient.api_deployment_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_api_deployment_path(path) + assert expected == actual + +def test_api_spec_path(): + project = "whelk" + location = "octopus" + api = "oyster" + version = "nudibranch" + spec = "cuttlefish" + expected = "projects/{project}/locations/{location}/apis/{api}/versions/{version}/specs/{spec}".format(project=project, location=location, api=api, version=version, spec=spec, ) + actual = RegistryClient.api_spec_path(project, location, api, version, spec) + assert expected == actual + + +def test_parse_api_spec_path(): + expected = { + "project": "mussel", + "location": "winkle", + "api": "nautilus", + "version": "scallop", + "spec": "abalone", + } + path = RegistryClient.api_spec_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_api_spec_path(path) + assert expected == actual + +def test_api_version_path(): + project = "squid" + location = "clam" + api = "whelk" + version = "octopus" + expected = "projects/{project}/locations/{location}/apis/{api}/versions/{version}".format(project=project, location=location, api=api, version=version, ) + actual = RegistryClient.api_version_path(project, location, api, version) + assert expected == actual + + +def test_parse_api_version_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "api": "cuttlefish", + "version": "mussel", + } + path = RegistryClient.api_version_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_api_version_path(path) + assert expected == actual + +def test_artifact_path(): + project = "winkle" + location = "nautilus" + artifact = "scallop" + expected = "projects/{project}/locations/{location}/artifacts/{artifact}".format(project=project, location=location, artifact=artifact, ) + actual = RegistryClient.artifact_path(project, location, artifact) + assert expected == actual + + +def test_parse_artifact_path(): + expected = { + "project": "abalone", + "location": "squid", + "artifact": "clam", + } + path = RegistryClient.artifact_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_artifact_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = RegistryClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = RegistryClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = RegistryClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = RegistryClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = RegistryClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = RegistryClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = RegistryClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = RegistryClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = RegistryClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = RegistryClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegistryClient.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(transports.RegistryTransport, '_prep_wrapped_messages') as prep: + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.RegistryTransport, '_prep_wrapped_messages') as prep: + transport_class = RegistryClient.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 = RegistryAsyncClient( + 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + +def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + +def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.cancel_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.CancelOperationRequest, + dict, +]) +def test_cancel_operation_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.DeleteOperationRequest, + dict, +]) +def test_delete_operation_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = '{}' + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + +def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_operations(request) + +@pytest.mark.parametrize("request_type", [ + operations_pb2.ListOperationsRequest, + dict, +]) +def test_list_operations_rest(request_type): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_delete_operation(transport: str = "grpc"): + client = RegistryClient( + 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 = RegistryAsyncClient( + 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 = RegistryClient( + 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 = RegistryAsyncClient( + 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 = RegistryClient( + 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 = RegistryAsyncClient( + 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 = RegistryClient( + 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 = RegistryAsyncClient( + 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 = RegistryClient( + 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 = RegistryAsyncClient( + 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"] + +def test_cancel_operation_from_dict(): + client = RegistryClient( + 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 + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = RegistryAsyncClient( + 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 = grpc_helpers_async.FakeUnaryUnaryCall( + None + ) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = RegistryClient( + 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.GetOperationRequest() + + # 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 + + # 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 = RegistryAsyncClient( + 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.GetOperationRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = RegistryClient( + 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.GetOperationRequest() + request.name = "locations" + + # 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() + + 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 + + # 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_get_operation_field_headers_async(): + client = RegistryAsyncClient( + 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.GetOperationRequest() + request.name = "locations" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # 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() + + +def test_list_operations(transport: str = "grpc"): + client = RegistryClient( + 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.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 + + # 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 = RegistryAsyncClient( + 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.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 = 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + +def test_list_operations_field_headers(): + client = RegistryClient( + 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.ListOperationsRequest() + request.name = "locations" + + # 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() + + 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"] +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = RegistryAsyncClient( + 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.ListOperationsRequest() + request.name = "locations" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_operations_from_dict(): + client = RegistryClient( + 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 = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = RegistryAsyncClient( + 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_list_locations(transport: str = "grpc"): + client = RegistryClient( + 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 = locations_pb2.ListLocationsRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + client = RegistryAsyncClient( + 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 = locations_pb2.ListLocationsRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = RegistryClient( + 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.ListLocationsRequest() + request.name = "locations" + + # 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() + + 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"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = RegistryAsyncClient( + 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.ListLocationsRequest() + request.name = "locations" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = RegistryClient( + 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.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = RegistryAsyncClient( + 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_get_location(transport: str = "grpc"): + client = RegistryClient( + 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 = locations_pb2.GetLocationRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = RegistryAsyncClient( + 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 = locations_pb2.GetLocationRequest() + + # 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 + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = RegistryClient( + 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" + + # 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() + + 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"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = RegistryAsyncClient( + 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" + + # 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_get_location_from_dict(): + client = RegistryClient( + 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() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = RegistryAsyncClient( + 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.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = RegistryClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = RegistryAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = RegistryClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = RegistryAsyncClient( + 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 = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + +def test_get_iam_policy(transport: str = "grpc"): + client = RegistryClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = RegistryAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = RegistryClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = RegistryAsyncClient( + 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 = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +def test_test_iam_permissions(transport: str = "grpc"): + client = RegistryClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = RegistryAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = RegistryClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = RegistryAsyncClient( + 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 = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = RegistryAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = RegistryClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + +@pytest.mark.parametrize("client_class,transport_class", [ + (RegistryClient, transports.RegistryGrpcTransport), + (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 1758100cc4b5aad6cea0560cb0f01413da02ba03 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 24 Feb 2023 02:32:01 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../services/provisioning/transports/rest.py | 52 +- .../services/registry/transports/rest.py | 116 +- .../types/provisioning_service.py | 2 + .../types/registry_models.py | 2 + .../types/registry_service.py | 2 + owl-bot-staging/v1/.coveragerc | 13 - owl-bot-staging/v1/.flake8 | 33 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - .../docs/apigee_registry_v1/provisioning.rst | 6 - .../v1/docs/apigee_registry_v1/registry.rst | 10 - .../v1/docs/apigee_registry_v1/services.rst | 7 - .../v1/docs/apigee_registry_v1/types.rst | 6 - owl-bot-staging/v1/docs/conf.py | 376 - owl-bot-staging/v1/docs/index.rst | 7 - .../google/cloud/apigee_registry/__init__.py | 135 - .../cloud/apigee_registry/gapic_version.py | 16 - .../v1/google/cloud/apigee_registry/py.typed | 2 - .../cloud/apigee_registry_v1/__init__.py | 136 - .../apigee_registry_v1/gapic_metadata.json | 617 - .../cloud/apigee_registry_v1/gapic_version.py | 16 - .../google/cloud/apigee_registry_v1/py.typed | 2 - .../apigee_registry_v1/services/__init__.py | 15 - .../services/provisioning/__init__.py | 22 - .../services/provisioning/async_client.py | 1166 - .../services/provisioning/client.py | 1365 - .../provisioning/transports/__init__.py | 38 - .../services/provisioning/transports/base.py | 269 - .../services/provisioning/transports/grpc.py | 527 - .../provisioning/transports/grpc_asyncio.py | 526 - .../services/provisioning/transports/rest.py | 1470 -- .../services/registry/__init__.py | 22 - .../services/registry/async_client.py | 4984 ---- .../services/registry/client.py | 4928 ---- .../services/registry/pagers.py | 866 - .../services/registry/transports/__init__.py | 38 - .../services/registry/transports/base.py | 1010 - .../services/registry/transports/grpc.py | 1362 - .../registry/transports/grpc_asyncio.py | 1361 - .../services/registry/transports/rest.py | 5357 ---- .../apigee_registry_v1/types/__init__.py | 128 - .../types/provisioning_service.py | 262 - .../types/registry_models.py | 573 - .../types/registry_service.py | 1222 - owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 184 - ...ated_provisioning_create_instance_async.py | 61 - ...rated_provisioning_create_instance_sync.py | 61 - ...ated_provisioning_delete_instance_async.py | 56 - ...rated_provisioning_delete_instance_sync.py | 56 - ...nerated_provisioning_get_instance_async.py | 52 - ...enerated_provisioning_get_instance_sync.py | 52 - ..._v1_generated_registry_create_api_async.py | 53 - ...ed_registry_create_api_deployment_async.py | 53 - ...ted_registry_create_api_deployment_sync.py | 53 - ...enerated_registry_create_api_spec_async.py | 53 - ...generated_registry_create_api_spec_sync.py | 53 - ...y_v1_generated_registry_create_api_sync.py | 53 - ...rated_registry_create_api_version_async.py | 53 - ...erated_registry_create_api_version_sync.py | 53 - ...enerated_registry_create_artifact_async.py | 53 - ...generated_registry_create_artifact_sync.py | 53 - ..._v1_generated_registry_delete_api_async.py | 50 - ...ed_registry_delete_api_deployment_async.py | 50 - ...ry_delete_api_deployment_revision_async.py | 52 - ...try_delete_api_deployment_revision_sync.py | 52 - ...ted_registry_delete_api_deployment_sync.py | 50 - ...enerated_registry_delete_api_spec_async.py | 50 - ...registry_delete_api_spec_revision_async.py | 52 - ..._registry_delete_api_spec_revision_sync.py | 52 - ...generated_registry_delete_api_spec_sync.py | 50 - ...y_v1_generated_registry_delete_api_sync.py | 50 - ...rated_registry_delete_api_version_async.py | 50 - ...erated_registry_delete_api_version_sync.py | 50 - ...enerated_registry_delete_artifact_async.py | 50 - ...generated_registry_delete_artifact_sync.py | 50 - ...try_v1_generated_registry_get_api_async.py | 52 - ...rated_registry_get_api_deployment_async.py | 52 - ...erated_registry_get_api_deployment_sync.py | 52 - ...1_generated_registry_get_api_spec_async.py | 52 - ...ed_registry_get_api_spec_contents_async.py | 52 - ...ted_registry_get_api_spec_contents_sync.py | 52 - ...v1_generated_registry_get_api_spec_sync.py | 52 - ...stry_v1_generated_registry_get_api_sync.py | 52 - ...enerated_registry_get_api_version_async.py | 52 - ...generated_registry_get_api_version_sync.py | 52 - ...1_generated_registry_get_artifact_async.py | 52 - ...ed_registry_get_artifact_contents_async.py | 52 - ...ted_registry_get_artifact_contents_sync.py | 52 - ...v1_generated_registry_get_artifact_sync.py | 52 - ...try_list_api_deployment_revisions_async.py | 53 - ...stry_list_api_deployment_revisions_sync.py | 53 - ...ted_registry_list_api_deployments_async.py | 53 - ...ated_registry_list_api_deployments_sync.py | 53 - ..._registry_list_api_spec_revisions_async.py | 53 - ...d_registry_list_api_spec_revisions_sync.py | 53 - ...generated_registry_list_api_specs_async.py | 53 - ..._generated_registry_list_api_specs_sync.py | 53 - ...erated_registry_list_api_versions_async.py | 53 - ...nerated_registry_list_api_versions_sync.py | 53 - ...y_v1_generated_registry_list_apis_async.py | 53 - ...ry_v1_generated_registry_list_apis_sync.py | 53 - ...generated_registry_list_artifacts_async.py | 53 - ..._generated_registry_list_artifacts_sync.py | 53 - ...nerated_registry_replace_artifact_async.py | 51 - ...enerated_registry_replace_artifact_sync.py | 51 - ..._registry_rollback_api_deployment_async.py | 53 - ...d_registry_rollback_api_deployment_sync.py | 53 - ...erated_registry_rollback_api_spec_async.py | 53 - ...nerated_registry_rollback_api_spec_sync.py | 53 - ...istry_tag_api_deployment_revision_async.py | 53 - ...gistry_tag_api_deployment_revision_sync.py | 53 - ...ed_registry_tag_api_spec_revision_async.py | 53 - ...ted_registry_tag_api_spec_revision_sync.py | 53 - ..._v1_generated_registry_update_api_async.py | 51 - ...ed_registry_update_api_deployment_async.py | 51 - ...ted_registry_update_api_deployment_sync.py | 51 - ...enerated_registry_update_api_spec_async.py | 51 - ...generated_registry_update_api_spec_sync.py | 51 - ...y_v1_generated_registry_update_api_sync.py | 51 - ...rated_registry_update_api_version_async.py | 51 - ...erated_registry_update_api_version_sync.py | 51 - ...tadata_google.cloud.apigeeregistry.v1.json | 6183 ----- .../fixup_apigee_registry_v1_keywords.py | 213 - owl-bot-staging/v1/setup.py | 91 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.7.txt | 10 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - owl-bot-staging/v1/tests/__init__.py | 16 - owl-bot-staging/v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/apigee_registry_v1/__init__.py | 16 - .../apigee_registry_v1/test_provisioning.py | 4396 ---- .../gapic/apigee_registry_v1/test_registry.py | 21303 ---------------- 137 files changed, 82 insertions(+), 65498 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc delete mode 100644 owl-bot-staging/v1/.flake8 delete mode 100644 owl-bot-staging/v1/MANIFEST.in delete mode 100644 owl-bot-staging/v1/README.rst delete mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst delete mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst delete mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/apigee_registry_v1/types.rst delete mode 100644 owl-bot-staging/v1/docs/conf.py delete mode 100644 owl-bot-staging/v1/docs/index.rst delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py delete mode 100644 owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py delete mode 100644 owl-bot-staging/v1/mypy.ini delete mode 100644 owl-bot-staging/v1/noxfile.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py delete mode 100644 owl-bot-staging/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1/tests/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py diff --git a/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py b/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py index bfc3dc1..ff8a0f3 100644 --- a/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py +++ b/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py @@ -17,7 +17,7 @@ import dataclasses import json # type: ignore import re -from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings from google.api_core import ( @@ -178,7 +178,7 @@ def pre_get_location( self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]], - ) -> locations_pb2.Location: + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -187,7 +187,7 @@ def pre_get_location( return request, metadata def post_get_location( - self, response: locations_pb2.GetLocationRequest + self, response: locations_pb2.Location ) -> locations_pb2.Location: """Post-rpc interceptor for get_location @@ -201,7 +201,7 @@ def pre_list_locations( self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]], - ) -> locations_pb2.ListLocationsResponse: + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -210,7 +210,7 @@ def pre_list_locations( return request, metadata def post_list_locations( - self, response: locations_pb2.ListLocationsRequest + self, response: locations_pb2.ListLocationsResponse ) -> locations_pb2.ListLocationsResponse: """Post-rpc interceptor for list_locations @@ -224,7 +224,7 @@ def pre_get_iam_policy( self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]], - ) -> policy_pb2.Policy: + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -232,9 +232,7 @@ def pre_get_iam_policy( """ return request, metadata - def post_get_iam_policy( - self, response: iam_policy_pb2.GetIamPolicyRequest - ) -> policy_pb2.Policy: + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy Override in a subclass to manipulate the response @@ -247,7 +245,7 @@ def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]], - ) -> policy_pb2.Policy: + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -255,9 +253,7 @@ def pre_set_iam_policy( """ return request, metadata - def post_set_iam_policy( - self, response: iam_policy_pb2.SetIamPolicyRequest - ) -> policy_pb2.Policy: + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy Override in a subclass to manipulate the response @@ -270,7 +266,7 @@ def pre_test_iam_permissions( self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]], - ) -> iam_policy_pb2.TestIamPermissionsResponse: + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -279,7 +275,7 @@ def pre_test_iam_permissions( return request, metadata def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsRequest + self, response: iam_policy_pb2.TestIamPermissionsResponse ) -> iam_policy_pb2.TestIamPermissionsResponse: """Post-rpc interceptor for test_iam_permissions @@ -293,7 +289,7 @@ def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]], - ) -> None: + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -301,9 +297,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: operations_pb2.CancelOperationRequest - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -316,7 +310,7 @@ def pre_delete_operation( self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]], - ) -> None: + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -324,9 +318,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: operations_pb2.DeleteOperationRequest - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -339,7 +331,7 @@ def pre_get_operation( self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]], - ) -> operations_pb2.Operation: + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -348,7 +340,7 @@ def pre_get_operation( return request, metadata def post_get_operation( - self, response: operations_pb2.GetOperationRequest + self, response: operations_pb2.Operation ) -> operations_pb2.Operation: """Post-rpc interceptor for get_operation @@ -362,7 +354,7 @@ def pre_list_operations( self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]], - ) -> operations_pb2.ListOperationsResponse: + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -371,7 +363,7 @@ def pre_list_operations( return request, metadata def post_list_operations( - self, response: operations_pb2.ListOperationsRequest + self, response: operations_pb2.ListOperationsResponse ) -> operations_pb2.ListOperationsResponse: """Post-rpc interceptor for list_operations @@ -537,7 +529,7 @@ class _CreateInstance(ProvisioningRestStub): def __hash__(self): return hash("CreateInstance") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "instanceId": "", } @@ -635,7 +627,7 @@ class _DeleteInstance(ProvisioningRestStub): def __hash__(self): return hash("DeleteInstance") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -722,7 +714,7 @@ class _GetInstance(ProvisioningRestStub): def __hash__(self): return hash("GetInstance") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): diff --git a/google/cloud/apigee_registry_v1/services/registry/transports/rest.py b/google/cloud/apigee_registry_v1/services/registry/transports/rest.py index ef32ad4..1d6494a 100644 --- a/google/cloud/apigee_registry_v1/services/registry/transports/rest.py +++ b/google/cloud/apigee_registry_v1/services/registry/transports/rest.py @@ -17,7 +17,7 @@ import dataclasses import json # type: ignore import re -from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union import warnings from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming @@ -1094,7 +1094,7 @@ def pre_get_location( self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]], - ) -> locations_pb2.Location: + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_location Override in a subclass to manipulate the request or metadata @@ -1103,7 +1103,7 @@ def pre_get_location( return request, metadata def post_get_location( - self, response: locations_pb2.GetLocationRequest + self, response: locations_pb2.Location ) -> locations_pb2.Location: """Post-rpc interceptor for get_location @@ -1117,7 +1117,7 @@ def pre_list_locations( self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]], - ) -> locations_pb2.ListLocationsResponse: + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_locations Override in a subclass to manipulate the request or metadata @@ -1126,7 +1126,7 @@ def pre_list_locations( return request, metadata def post_list_locations( - self, response: locations_pb2.ListLocationsRequest + self, response: locations_pb2.ListLocationsResponse ) -> locations_pb2.ListLocationsResponse: """Post-rpc interceptor for list_locations @@ -1140,7 +1140,7 @@ def pre_get_iam_policy( self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]], - ) -> policy_pb2.Policy: + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_iam_policy Override in a subclass to manipulate the request or metadata @@ -1148,9 +1148,7 @@ def pre_get_iam_policy( """ return request, metadata - def post_get_iam_policy( - self, response: iam_policy_pb2.GetIamPolicyRequest - ) -> policy_pb2.Policy: + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for get_iam_policy Override in a subclass to manipulate the response @@ -1163,7 +1161,7 @@ def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]], - ) -> policy_pb2.Policy: + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for set_iam_policy Override in a subclass to manipulate the request or metadata @@ -1171,9 +1169,7 @@ def pre_set_iam_policy( """ return request, metadata - def post_set_iam_policy( - self, response: iam_policy_pb2.SetIamPolicyRequest - ) -> policy_pb2.Policy: + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: """Post-rpc interceptor for set_iam_policy Override in a subclass to manipulate the response @@ -1186,7 +1182,7 @@ def pre_test_iam_permissions( self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]], - ) -> iam_policy_pb2.TestIamPermissionsResponse: + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for test_iam_permissions Override in a subclass to manipulate the request or metadata @@ -1195,7 +1191,7 @@ def pre_test_iam_permissions( return request, metadata def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsRequest + self, response: iam_policy_pb2.TestIamPermissionsResponse ) -> iam_policy_pb2.TestIamPermissionsResponse: """Post-rpc interceptor for test_iam_permissions @@ -1209,7 +1205,7 @@ def pre_cancel_operation( self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]], - ) -> None: + ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for cancel_operation Override in a subclass to manipulate the request or metadata @@ -1217,9 +1213,7 @@ def pre_cancel_operation( """ return request, metadata - def post_cancel_operation( - self, response: operations_pb2.CancelOperationRequest - ) -> None: + def post_cancel_operation(self, response: None) -> None: """Post-rpc interceptor for cancel_operation Override in a subclass to manipulate the response @@ -1232,7 +1226,7 @@ def pre_delete_operation( self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]], - ) -> None: + ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for delete_operation Override in a subclass to manipulate the request or metadata @@ -1240,9 +1234,7 @@ def pre_delete_operation( """ return request, metadata - def post_delete_operation( - self, response: operations_pb2.DeleteOperationRequest - ) -> None: + def post_delete_operation(self, response: None) -> None: """Post-rpc interceptor for delete_operation Override in a subclass to manipulate the response @@ -1255,7 +1247,7 @@ def pre_get_operation( self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]], - ) -> operations_pb2.Operation: + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for get_operation Override in a subclass to manipulate the request or metadata @@ -1264,7 +1256,7 @@ def pre_get_operation( return request, metadata def post_get_operation( - self, response: operations_pb2.GetOperationRequest + self, response: operations_pb2.Operation ) -> operations_pb2.Operation: """Post-rpc interceptor for get_operation @@ -1278,7 +1270,7 @@ def pre_list_operations( self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]], - ) -> operations_pb2.ListOperationsResponse: + ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: """Pre-rpc interceptor for list_operations Override in a subclass to manipulate the request or metadata @@ -1287,7 +1279,7 @@ def pre_list_operations( return request, metadata def post_list_operations( - self, response: operations_pb2.ListOperationsRequest + self, response: operations_pb2.ListOperationsResponse ) -> operations_pb2.ListOperationsResponse: """Post-rpc interceptor for list_operations @@ -1399,7 +1391,7 @@ class _CreateApi(RegistryRestStub): def __hash__(self): return hash("CreateApi") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "apiId": "", } @@ -1499,7 +1491,7 @@ class _CreateApiDeployment(RegistryRestStub): def __hash__(self): return hash("CreateApiDeployment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "apiDeploymentId": "", } @@ -1609,7 +1601,7 @@ class _CreateApiSpec(RegistryRestStub): def __hash__(self): return hash("CreateApiSpec") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "apiSpecId": "", } @@ -1720,7 +1712,7 @@ class _CreateApiVersion(RegistryRestStub): def __hash__(self): return hash("CreateApiVersion") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "apiVersionId": "", } @@ -1822,7 +1814,7 @@ class _CreateArtifact(RegistryRestStub): def __hash__(self): return hash("CreateArtifact") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { "artifactId": "", } @@ -1950,7 +1942,7 @@ class _DeleteApi(RegistryRestStub): def __hash__(self): return hash("DeleteApi") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2024,7 +2016,7 @@ class _DeleteApiDeployment(RegistryRestStub): def __hash__(self): return hash("DeleteApiDeployment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2102,7 +2094,7 @@ class _DeleteApiDeploymentRevision(RegistryRestStub): def __hash__(self): return hash("DeleteApiDeploymentRevision") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2202,7 +2194,7 @@ class _DeleteApiSpec(RegistryRestStub): def __hash__(self): return hash("DeleteApiSpec") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2276,7 +2268,7 @@ class _DeleteApiSpecRevision(RegistryRestStub): def __hash__(self): return hash("DeleteApiSpecRevision") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2380,7 +2372,7 @@ class _DeleteApiVersion(RegistryRestStub): def __hash__(self): return hash("DeleteApiVersion") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2456,7 +2448,7 @@ class _DeleteArtifact(RegistryRestStub): def __hash__(self): return hash("DeleteArtifact") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2546,7 +2538,7 @@ class _GetApi(RegistryRestStub): def __hash__(self): return hash("GetApi") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2635,7 +2627,7 @@ class _GetApiDeployment(RegistryRestStub): def __hash__(self): return hash("GetApiDeployment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2732,7 +2724,7 @@ class _GetApiSpec(RegistryRestStub): def __hash__(self): return hash("GetApiSpec") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2832,7 +2824,7 @@ class _GetApiSpecContents(RegistryRestStub): def __hash__(self): return hash("GetApiSpecContents") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -2971,7 +2963,7 @@ class _GetApiVersion(RegistryRestStub): def __hash__(self): return hash("GetApiVersion") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3060,7 +3052,7 @@ class _GetArtifact(RegistryRestStub): def __hash__(self): return hash("GetArtifact") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3173,7 +3165,7 @@ class _GetArtifactContents(RegistryRestStub): def __hash__(self): return hash("GetArtifactContents") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3328,7 +3320,7 @@ class _ListApiDeploymentRevisions(RegistryRestStub): def __hash__(self): return hash("ListApiDeploymentRevisions") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3421,7 +3413,7 @@ class _ListApiDeployments(RegistryRestStub): def __hash__(self): return hash("ListApiDeployments") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3513,7 +3505,7 @@ class _ListApis(RegistryRestStub): def __hash__(self): return hash("ListApis") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3599,7 +3591,7 @@ class _ListApiSpecRevisions(RegistryRestStub): def __hash__(self): return hash("ListApiSpecRevisions") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3691,7 +3683,7 @@ class _ListApiSpecs(RegistryRestStub): def __hash__(self): return hash("ListApiSpecs") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3777,7 +3769,7 @@ class _ListApiVersions(RegistryRestStub): def __hash__(self): return hash("ListApiVersions") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3865,7 +3857,7 @@ class _ListArtifacts(RegistryRestStub): def __hash__(self): return hash("ListArtifacts") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -3967,7 +3959,7 @@ class _ReplaceArtifact(RegistryRestStub): def __hash__(self): return hash("ReplaceArtifact") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4095,7 +4087,7 @@ class _RollbackApiDeployment(RegistryRestStub): def __hash__(self): return hash("RollbackApiDeployment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4203,7 +4195,7 @@ class _RollbackApiSpec(RegistryRestStub): def __hash__(self): return hash("RollbackApiSpec") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4314,7 +4306,7 @@ class _TagApiDeploymentRevision(RegistryRestStub): def __hash__(self): return hash("TagApiDeploymentRevision") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4423,7 +4415,7 @@ class _TagApiSpecRevision(RegistryRestStub): def __hash__(self): return hash("TagApiSpecRevision") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4536,7 +4528,7 @@ class _UpdateApi(RegistryRestStub): def __hash__(self): return hash("UpdateApi") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4634,7 +4626,7 @@ class _UpdateApiDeployment(RegistryRestStub): def __hash__(self): return hash("UpdateApiDeployment") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4742,7 +4734,7 @@ class _UpdateApiSpec(RegistryRestStub): def __hash__(self): return hash("UpdateApiSpec") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): @@ -4851,7 +4843,7 @@ class _UpdateApiVersion(RegistryRestStub): def __hash__(self): return hash("UpdateApiVersion") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @classmethod def _get_unset_required_fields(cls, message_dict): diff --git a/google/cloud/apigee_registry_v1/types/provisioning_service.py b/google/cloud/apigee_registry_v1/types/provisioning_service.py index 5340744..3a0f0ad 100644 --- a/google/cloud/apigee_registry_v1/types/provisioning_service.py +++ b/google/cloud/apigee_registry_v1/types/provisioning_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import timestamp_pb2 # type: ignore diff --git a/google/cloud/apigee_registry_v1/types/registry_models.py b/google/cloud/apigee_registry_v1/types/registry_models.py index 63be5b0..83bcdec 100644 --- a/google/cloud/apigee_registry_v1/types/registry_models.py +++ b/google/cloud/apigee_registry_v1/types/registry_models.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import timestamp_pb2 # type: ignore diff --git a/google/cloud/apigee_registry_v1/types/registry_service.py b/google/cloud/apigee_registry_v1/types/registry_service.py index 155398c..8525775 100644 --- a/google/cloud/apigee_registry_v1/types/registry_service.py +++ b/google/cloud/apigee_registry_v1/types/registry_service.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import field_mask_pb2 # type: ignore diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 4deb36f..0000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/apigee_registry/__init__.py - google/cloud/apigee_registry/gapic_version.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ diff --git a/owl-bot-staging/v1/.flake8 b/owl-bot-staging/v1/.flake8 deleted file mode 100644 index 29227d4..0000000 --- a/owl-bot-staging/v1/.flake8 +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://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 by synthtool. DO NOT EDIT! -[flake8] -ignore = E203, E266, E501, W503 -exclude = - # Exclude generated code. - **/proto/** - **/gapic/** - **/services/** - **/types/** - *_pb2.py - - # Standard linting exemptions. - **/.nox/** - __pycache__, - .git, - *.pyc, - conf.py diff --git a/owl-bot-staging/v1/MANIFEST.in b/owl-bot-staging/v1/MANIFEST.in deleted file mode 100644 index 245d857..0000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/apigee_registry *.py -recursive-include google/cloud/apigee_registry_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index a6898f0..0000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Apigee Registry API -================================================= - -Quick Start ------------ - -In order to use this library, you first need to go through the following steps: - -1. `Select or create a Cloud Platform project.`_ -2. `Enable billing for your project.`_ -3. Enable the Google Cloud Apigee Registry API. -4. `Setup Authentication.`_ - -.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project -.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project -.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html - -Installation -~~~~~~~~~~~~ - -Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to -create isolated Python environments. The basic problem it addresses is one of -dependencies and versions, and indirectly permissions. - -With `virtualenv`_, it's possible to install this library without needing system -install permissions, and without clashing with the installed system -dependencies. - -.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/ - - -Mac/Linux -^^^^^^^^^ - -.. code-block:: console - - python3 -m venv - source /bin/activate - /bin/pip install /path/to/library - - -Windows -^^^^^^^ - -.. code-block:: console - - python3 -m venv - \Scripts\activate - \Scripts\pip.exe install \path\to\library diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst deleted file mode 100644 index 08a647d..0000000 --- a/owl-bot-staging/v1/docs/apigee_registry_v1/provisioning.rst +++ /dev/null @@ -1,6 +0,0 @@ -Provisioning ------------------------------- - -.. automodule:: google.cloud.apigee_registry_v1.services.provisioning - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst deleted file mode 100644 index dc4e73a..0000000 --- a/owl-bot-staging/v1/docs/apigee_registry_v1/registry.rst +++ /dev/null @@ -1,10 +0,0 @@ -Registry --------------------------- - -.. automodule:: google.cloud.apigee_registry_v1.services.registry - :members: - :inherited-members: - -.. automodule:: google.cloud.apigee_registry_v1.services.registry.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/services.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/services.rst deleted file mode 100644 index 651781f..0000000 --- a/owl-bot-staging/v1/docs/apigee_registry_v1/services.rst +++ /dev/null @@ -1,7 +0,0 @@ -Services for Google Cloud Apigee Registry v1 API -================================================ -.. toctree:: - :maxdepth: 2 - - provisioning - registry diff --git a/owl-bot-staging/v1/docs/apigee_registry_v1/types.rst b/owl-bot-staging/v1/docs/apigee_registry_v1/types.rst deleted file mode 100644 index ca720e7..0000000 --- a/owl-bot-staging/v1/docs/apigee_registry_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Apigee Registry v1 API -============================================= - -.. automodule:: google.cloud.apigee_registry_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1/docs/conf.py b/owl-bot-staging/v1/docs/conf.py deleted file mode 100644 index 9d76789..0000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- 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. -# -# -# google-cloud-apigee-registry documentation build configuration file -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys -import os -import shlex - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("..")) - -__version__ = "0.1.0" - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "4.0.1" - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinx.ext.autosummary", - "sphinx.ext.intersphinx", - "sphinx.ext.coverage", - "sphinx.ext.napoleon", - "sphinx.ext.todo", - "sphinx.ext.viewcode", -] - -# autodoc/autosummary flags -autoclass_content = "both" -autodoc_default_flags = ["members"] -autosummary_generate = True - - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -# Allow markdown includes (so releases.md can include CHANGLEOG.md) -# http://www.sphinx-doc.org/en/master/markdown.html -source_parsers = {".md": "recommonmark.parser.CommonMarkParser"} - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -source_suffix = [".rst", ".md"] - -# The encoding of source files. -# source_encoding = 'utf-8-sig' - -# The root toctree document. -root_doc = "index" - -# General information about the project. -project = u"google-cloud-apigee-registry" -copyright = u"2022, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-apigee-registry-doc" - -# -- Options for warnings ------------------------------------------------------ - - -suppress_warnings = [ - # Temporarily suppress this to avoid "more than one target found for - # cross-reference" warning, which are intractable for us to avoid while in - # a mono-repo. - # See https://github.com/sphinx-doc/sphinx/blob - # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 - "ref.python" -] - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', - # Latex figure (float) alignment - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - root_doc, - "google-cloud-apigee-registry.tex", - u"google-cloud-apigee-registry Documentation", - author, - "manual", - ) -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - root_doc, - "google-cloud-apigee-registry", - u"Google Cloud Apigee Registry Documentation", - [author], - 1, - ) -] - -# If true, show URL addresses after external links. -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - root_doc, - "google-cloud-apigee-registry", - u"google-cloud-apigee-registry Documentation", - author, - "google-cloud-apigee-registry", - "GAPIC library for Google Cloud Apigee Registry API", - "APIs", - ) -] - -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "gax": ("https://gax-python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google-gax": ("https://gax-python.readthedocs.io/en/latest/", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), - "requests": ("http://requests.kennethreitz.org/en/stable/", None), - "proto": ("https://proto-plus-python.readthedocs.io/en/stable", None), - "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), -} - - -# Napoleon settings -napoleon_google_docstring = True -napoleon_numpy_docstring = True -napoleon_include_private_with_doc = False -napoleon_include_special_with_doc = True -napoleon_use_admonition_for_examples = False -napoleon_use_admonition_for_notes = False -napoleon_use_admonition_for_references = False -napoleon_use_ivar = False -napoleon_use_param = True -napoleon_use_rtype = True diff --git a/owl-bot-staging/v1/docs/index.rst b/owl-bot-staging/v1/docs/index.rst deleted file mode 100644 index c450000..0000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - apigee_registry_v1/services - apigee_registry_v1/types diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py deleted file mode 100644 index 8a876f3..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry/__init__.py +++ /dev/null @@ -1,135 +0,0 @@ -# -*- 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. -# -from google.cloud.apigee_registry import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.apigee_registry_v1.services.provisioning.client import ProvisioningClient -from google.cloud.apigee_registry_v1.services.provisioning.async_client import ProvisioningAsyncClient -from google.cloud.apigee_registry_v1.services.registry.client import RegistryClient -from google.cloud.apigee_registry_v1.services.registry.async_client import RegistryAsyncClient - -from google.cloud.apigee_registry_v1.types.provisioning_service import CreateInstanceRequest -from google.cloud.apigee_registry_v1.types.provisioning_service import DeleteInstanceRequest -from google.cloud.apigee_registry_v1.types.provisioning_service import GetInstanceRequest -from google.cloud.apigee_registry_v1.types.provisioning_service import Instance -from google.cloud.apigee_registry_v1.types.provisioning_service import OperationMetadata -from google.cloud.apigee_registry_v1.types.registry_models import Api -from google.cloud.apigee_registry_v1.types.registry_models import ApiDeployment -from google.cloud.apigee_registry_v1.types.registry_models import ApiSpec -from google.cloud.apigee_registry_v1.types.registry_models import ApiVersion -from google.cloud.apigee_registry_v1.types.registry_models import Artifact -from google.cloud.apigee_registry_v1.types.registry_service import CreateApiDeploymentRequest -from google.cloud.apigee_registry_v1.types.registry_service import CreateApiRequest -from google.cloud.apigee_registry_v1.types.registry_service import CreateApiSpecRequest -from google.cloud.apigee_registry_v1.types.registry_service import CreateApiVersionRequest -from google.cloud.apigee_registry_v1.types.registry_service import CreateArtifactRequest -from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiDeploymentRequest -from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiDeploymentRevisionRequest -from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiRequest -from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiSpecRequest -from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiSpecRevisionRequest -from google.cloud.apigee_registry_v1.types.registry_service import DeleteApiVersionRequest -from google.cloud.apigee_registry_v1.types.registry_service import DeleteArtifactRequest -from google.cloud.apigee_registry_v1.types.registry_service import GetApiDeploymentRequest -from google.cloud.apigee_registry_v1.types.registry_service import GetApiRequest -from google.cloud.apigee_registry_v1.types.registry_service import GetApiSpecContentsRequest -from google.cloud.apigee_registry_v1.types.registry_service import GetApiSpecRequest -from google.cloud.apigee_registry_v1.types.registry_service import GetApiVersionRequest -from google.cloud.apigee_registry_v1.types.registry_service import GetArtifactContentsRequest -from google.cloud.apigee_registry_v1.types.registry_service import GetArtifactRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentRevisionsRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentRevisionsResponse -from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentsRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListApiDeploymentsResponse -from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecRevisionsRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecRevisionsResponse -from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecsRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListApiSpecsResponse -from google.cloud.apigee_registry_v1.types.registry_service import ListApisRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListApisResponse -from google.cloud.apigee_registry_v1.types.registry_service import ListApiVersionsRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListApiVersionsResponse -from google.cloud.apigee_registry_v1.types.registry_service import ListArtifactsRequest -from google.cloud.apigee_registry_v1.types.registry_service import ListArtifactsResponse -from google.cloud.apigee_registry_v1.types.registry_service import ReplaceArtifactRequest -from google.cloud.apigee_registry_v1.types.registry_service import RollbackApiDeploymentRequest -from google.cloud.apigee_registry_v1.types.registry_service import RollbackApiSpecRequest -from google.cloud.apigee_registry_v1.types.registry_service import TagApiDeploymentRevisionRequest -from google.cloud.apigee_registry_v1.types.registry_service import TagApiSpecRevisionRequest -from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiDeploymentRequest -from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiRequest -from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiSpecRequest -from google.cloud.apigee_registry_v1.types.registry_service import UpdateApiVersionRequest - -__all__ = ('ProvisioningClient', - 'ProvisioningAsyncClient', - 'RegistryClient', - 'RegistryAsyncClient', - 'CreateInstanceRequest', - 'DeleteInstanceRequest', - 'GetInstanceRequest', - 'Instance', - 'OperationMetadata', - 'Api', - 'ApiDeployment', - 'ApiSpec', - 'ApiVersion', - 'Artifact', - 'CreateApiDeploymentRequest', - 'CreateApiRequest', - 'CreateApiSpecRequest', - 'CreateApiVersionRequest', - 'CreateArtifactRequest', - 'DeleteApiDeploymentRequest', - 'DeleteApiDeploymentRevisionRequest', - 'DeleteApiRequest', - 'DeleteApiSpecRequest', - 'DeleteApiSpecRevisionRequest', - 'DeleteApiVersionRequest', - 'DeleteArtifactRequest', - 'GetApiDeploymentRequest', - 'GetApiRequest', - 'GetApiSpecContentsRequest', - 'GetApiSpecRequest', - 'GetApiVersionRequest', - 'GetArtifactContentsRequest', - 'GetArtifactRequest', - 'ListApiDeploymentRevisionsRequest', - 'ListApiDeploymentRevisionsResponse', - 'ListApiDeploymentsRequest', - 'ListApiDeploymentsResponse', - 'ListApiSpecRevisionsRequest', - 'ListApiSpecRevisionsResponse', - 'ListApiSpecsRequest', - 'ListApiSpecsResponse', - 'ListApisRequest', - 'ListApisResponse', - 'ListApiVersionsRequest', - 'ListApiVersionsResponse', - 'ListArtifactsRequest', - 'ListArtifactsResponse', - 'ReplaceArtifactRequest', - 'RollbackApiDeploymentRequest', - 'RollbackApiSpecRequest', - 'TagApiDeploymentRevisionRequest', - 'TagApiSpecRevisionRequest', - 'UpdateApiDeploymentRequest', - 'UpdateApiRequest', - 'UpdateApiSpecRequest', - 'UpdateApiVersionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py b/owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry/py.typed b/owl-bot-staging/v1/google/cloud/apigee_registry/py.typed deleted file mode 100644 index 4602793..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-apigee-registry package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py deleted file mode 100644 index 83d259d..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/__init__.py +++ /dev/null @@ -1,136 +0,0 @@ -# -*- 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. -# -from google.cloud.apigee_registry_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.provisioning import ProvisioningClient -from .services.provisioning import ProvisioningAsyncClient -from .services.registry import RegistryClient -from .services.registry import RegistryAsyncClient - -from .types.provisioning_service import CreateInstanceRequest -from .types.provisioning_service import DeleteInstanceRequest -from .types.provisioning_service import GetInstanceRequest -from .types.provisioning_service import Instance -from .types.provisioning_service import OperationMetadata -from .types.registry_models import Api -from .types.registry_models import ApiDeployment -from .types.registry_models import ApiSpec -from .types.registry_models import ApiVersion -from .types.registry_models import Artifact -from .types.registry_service import CreateApiDeploymentRequest -from .types.registry_service import CreateApiRequest -from .types.registry_service import CreateApiSpecRequest -from .types.registry_service import CreateApiVersionRequest -from .types.registry_service import CreateArtifactRequest -from .types.registry_service import DeleteApiDeploymentRequest -from .types.registry_service import DeleteApiDeploymentRevisionRequest -from .types.registry_service import DeleteApiRequest -from .types.registry_service import DeleteApiSpecRequest -from .types.registry_service import DeleteApiSpecRevisionRequest -from .types.registry_service import DeleteApiVersionRequest -from .types.registry_service import DeleteArtifactRequest -from .types.registry_service import GetApiDeploymentRequest -from .types.registry_service import GetApiRequest -from .types.registry_service import GetApiSpecContentsRequest -from .types.registry_service import GetApiSpecRequest -from .types.registry_service import GetApiVersionRequest -from .types.registry_service import GetArtifactContentsRequest -from .types.registry_service import GetArtifactRequest -from .types.registry_service import ListApiDeploymentRevisionsRequest -from .types.registry_service import ListApiDeploymentRevisionsResponse -from .types.registry_service import ListApiDeploymentsRequest -from .types.registry_service import ListApiDeploymentsResponse -from .types.registry_service import ListApiSpecRevisionsRequest -from .types.registry_service import ListApiSpecRevisionsResponse -from .types.registry_service import ListApiSpecsRequest -from .types.registry_service import ListApiSpecsResponse -from .types.registry_service import ListApisRequest -from .types.registry_service import ListApisResponse -from .types.registry_service import ListApiVersionsRequest -from .types.registry_service import ListApiVersionsResponse -from .types.registry_service import ListArtifactsRequest -from .types.registry_service import ListArtifactsResponse -from .types.registry_service import ReplaceArtifactRequest -from .types.registry_service import RollbackApiDeploymentRequest -from .types.registry_service import RollbackApiSpecRequest -from .types.registry_service import TagApiDeploymentRevisionRequest -from .types.registry_service import TagApiSpecRevisionRequest -from .types.registry_service import UpdateApiDeploymentRequest -from .types.registry_service import UpdateApiRequest -from .types.registry_service import UpdateApiSpecRequest -from .types.registry_service import UpdateApiVersionRequest - -__all__ = ( - 'ProvisioningAsyncClient', - 'RegistryAsyncClient', -'Api', -'ApiDeployment', -'ApiSpec', -'ApiVersion', -'Artifact', -'CreateApiDeploymentRequest', -'CreateApiRequest', -'CreateApiSpecRequest', -'CreateApiVersionRequest', -'CreateArtifactRequest', -'CreateInstanceRequest', -'DeleteApiDeploymentRequest', -'DeleteApiDeploymentRevisionRequest', -'DeleteApiRequest', -'DeleteApiSpecRequest', -'DeleteApiSpecRevisionRequest', -'DeleteApiVersionRequest', -'DeleteArtifactRequest', -'DeleteInstanceRequest', -'GetApiDeploymentRequest', -'GetApiRequest', -'GetApiSpecContentsRequest', -'GetApiSpecRequest', -'GetApiVersionRequest', -'GetArtifactContentsRequest', -'GetArtifactRequest', -'GetInstanceRequest', -'Instance', -'ListApiDeploymentRevisionsRequest', -'ListApiDeploymentRevisionsResponse', -'ListApiDeploymentsRequest', -'ListApiDeploymentsResponse', -'ListApiSpecRevisionsRequest', -'ListApiSpecRevisionsResponse', -'ListApiSpecsRequest', -'ListApiSpecsResponse', -'ListApiVersionsRequest', -'ListApiVersionsResponse', -'ListApisRequest', -'ListApisResponse', -'ListArtifactsRequest', -'ListArtifactsResponse', -'OperationMetadata', -'ProvisioningClient', -'RegistryClient', -'ReplaceArtifactRequest', -'RollbackApiDeploymentRequest', -'RollbackApiSpecRequest', -'TagApiDeploymentRevisionRequest', -'TagApiSpecRevisionRequest', -'UpdateApiDeploymentRequest', -'UpdateApiRequest', -'UpdateApiSpecRequest', -'UpdateApiVersionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json deleted file mode 100644 index 20b6f38..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_metadata.json +++ /dev/null @@ -1,617 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.apigee_registry_v1", - "protoPackage": "google.cloud.apigeeregistry.v1", - "schema": "1.0", - "services": { - "Provisioning": { - "clients": { - "grpc": { - "libraryClient": "ProvisioningClient", - "rpcs": { - "CreateInstance": { - "methods": [ - "create_instance" - ] - }, - "DeleteInstance": { - "methods": [ - "delete_instance" - ] - }, - "GetInstance": { - "methods": [ - "get_instance" - ] - } - } - }, - "grpc-async": { - "libraryClient": "ProvisioningAsyncClient", - "rpcs": { - "CreateInstance": { - "methods": [ - "create_instance" - ] - }, - "DeleteInstance": { - "methods": [ - "delete_instance" - ] - }, - "GetInstance": { - "methods": [ - "get_instance" - ] - } - } - }, - "rest": { - "libraryClient": "ProvisioningClient", - "rpcs": { - "CreateInstance": { - "methods": [ - "create_instance" - ] - }, - "DeleteInstance": { - "methods": [ - "delete_instance" - ] - }, - "GetInstance": { - "methods": [ - "get_instance" - ] - } - } - } - } - }, - "Registry": { - "clients": { - "grpc": { - "libraryClient": "RegistryClient", - "rpcs": { - "CreateApi": { - "methods": [ - "create_api" - ] - }, - "CreateApiDeployment": { - "methods": [ - "create_api_deployment" - ] - }, - "CreateApiSpec": { - "methods": [ - "create_api_spec" - ] - }, - "CreateApiVersion": { - "methods": [ - "create_api_version" - ] - }, - "CreateArtifact": { - "methods": [ - "create_artifact" - ] - }, - "DeleteApi": { - "methods": [ - "delete_api" - ] - }, - "DeleteApiDeployment": { - "methods": [ - "delete_api_deployment" - ] - }, - "DeleteApiDeploymentRevision": { - "methods": [ - "delete_api_deployment_revision" - ] - }, - "DeleteApiSpec": { - "methods": [ - "delete_api_spec" - ] - }, - "DeleteApiSpecRevision": { - "methods": [ - "delete_api_spec_revision" - ] - }, - "DeleteApiVersion": { - "methods": [ - "delete_api_version" - ] - }, - "DeleteArtifact": { - "methods": [ - "delete_artifact" - ] - }, - "GetApi": { - "methods": [ - "get_api" - ] - }, - "GetApiDeployment": { - "methods": [ - "get_api_deployment" - ] - }, - "GetApiSpec": { - "methods": [ - "get_api_spec" - ] - }, - "GetApiSpecContents": { - "methods": [ - "get_api_spec_contents" - ] - }, - "GetApiVersion": { - "methods": [ - "get_api_version" - ] - }, - "GetArtifact": { - "methods": [ - "get_artifact" - ] - }, - "GetArtifactContents": { - "methods": [ - "get_artifact_contents" - ] - }, - "ListApiDeploymentRevisions": { - "methods": [ - "list_api_deployment_revisions" - ] - }, - "ListApiDeployments": { - "methods": [ - "list_api_deployments" - ] - }, - "ListApiSpecRevisions": { - "methods": [ - "list_api_spec_revisions" - ] - }, - "ListApiSpecs": { - "methods": [ - "list_api_specs" - ] - }, - "ListApiVersions": { - "methods": [ - "list_api_versions" - ] - }, - "ListApis": { - "methods": [ - "list_apis" - ] - }, - "ListArtifacts": { - "methods": [ - "list_artifacts" - ] - }, - "ReplaceArtifact": { - "methods": [ - "replace_artifact" - ] - }, - "RollbackApiDeployment": { - "methods": [ - "rollback_api_deployment" - ] - }, - "RollbackApiSpec": { - "methods": [ - "rollback_api_spec" - ] - }, - "TagApiDeploymentRevision": { - "methods": [ - "tag_api_deployment_revision" - ] - }, - "TagApiSpecRevision": { - "methods": [ - "tag_api_spec_revision" - ] - }, - "UpdateApi": { - "methods": [ - "update_api" - ] - }, - "UpdateApiDeployment": { - "methods": [ - "update_api_deployment" - ] - }, - "UpdateApiSpec": { - "methods": [ - "update_api_spec" - ] - }, - "UpdateApiVersion": { - "methods": [ - "update_api_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "RegistryAsyncClient", - "rpcs": { - "CreateApi": { - "methods": [ - "create_api" - ] - }, - "CreateApiDeployment": { - "methods": [ - "create_api_deployment" - ] - }, - "CreateApiSpec": { - "methods": [ - "create_api_spec" - ] - }, - "CreateApiVersion": { - "methods": [ - "create_api_version" - ] - }, - "CreateArtifact": { - "methods": [ - "create_artifact" - ] - }, - "DeleteApi": { - "methods": [ - "delete_api" - ] - }, - "DeleteApiDeployment": { - "methods": [ - "delete_api_deployment" - ] - }, - "DeleteApiDeploymentRevision": { - "methods": [ - "delete_api_deployment_revision" - ] - }, - "DeleteApiSpec": { - "methods": [ - "delete_api_spec" - ] - }, - "DeleteApiSpecRevision": { - "methods": [ - "delete_api_spec_revision" - ] - }, - "DeleteApiVersion": { - "methods": [ - "delete_api_version" - ] - }, - "DeleteArtifact": { - "methods": [ - "delete_artifact" - ] - }, - "GetApi": { - "methods": [ - "get_api" - ] - }, - "GetApiDeployment": { - "methods": [ - "get_api_deployment" - ] - }, - "GetApiSpec": { - "methods": [ - "get_api_spec" - ] - }, - "GetApiSpecContents": { - "methods": [ - "get_api_spec_contents" - ] - }, - "GetApiVersion": { - "methods": [ - "get_api_version" - ] - }, - "GetArtifact": { - "methods": [ - "get_artifact" - ] - }, - "GetArtifactContents": { - "methods": [ - "get_artifact_contents" - ] - }, - "ListApiDeploymentRevisions": { - "methods": [ - "list_api_deployment_revisions" - ] - }, - "ListApiDeployments": { - "methods": [ - "list_api_deployments" - ] - }, - "ListApiSpecRevisions": { - "methods": [ - "list_api_spec_revisions" - ] - }, - "ListApiSpecs": { - "methods": [ - "list_api_specs" - ] - }, - "ListApiVersions": { - "methods": [ - "list_api_versions" - ] - }, - "ListApis": { - "methods": [ - "list_apis" - ] - }, - "ListArtifacts": { - "methods": [ - "list_artifacts" - ] - }, - "ReplaceArtifact": { - "methods": [ - "replace_artifact" - ] - }, - "RollbackApiDeployment": { - "methods": [ - "rollback_api_deployment" - ] - }, - "RollbackApiSpec": { - "methods": [ - "rollback_api_spec" - ] - }, - "TagApiDeploymentRevision": { - "methods": [ - "tag_api_deployment_revision" - ] - }, - "TagApiSpecRevision": { - "methods": [ - "tag_api_spec_revision" - ] - }, - "UpdateApi": { - "methods": [ - "update_api" - ] - }, - "UpdateApiDeployment": { - "methods": [ - "update_api_deployment" - ] - }, - "UpdateApiSpec": { - "methods": [ - "update_api_spec" - ] - }, - "UpdateApiVersion": { - "methods": [ - "update_api_version" - ] - } - } - }, - "rest": { - "libraryClient": "RegistryClient", - "rpcs": { - "CreateApi": { - "methods": [ - "create_api" - ] - }, - "CreateApiDeployment": { - "methods": [ - "create_api_deployment" - ] - }, - "CreateApiSpec": { - "methods": [ - "create_api_spec" - ] - }, - "CreateApiVersion": { - "methods": [ - "create_api_version" - ] - }, - "CreateArtifact": { - "methods": [ - "create_artifact" - ] - }, - "DeleteApi": { - "methods": [ - "delete_api" - ] - }, - "DeleteApiDeployment": { - "methods": [ - "delete_api_deployment" - ] - }, - "DeleteApiDeploymentRevision": { - "methods": [ - "delete_api_deployment_revision" - ] - }, - "DeleteApiSpec": { - "methods": [ - "delete_api_spec" - ] - }, - "DeleteApiSpecRevision": { - "methods": [ - "delete_api_spec_revision" - ] - }, - "DeleteApiVersion": { - "methods": [ - "delete_api_version" - ] - }, - "DeleteArtifact": { - "methods": [ - "delete_artifact" - ] - }, - "GetApi": { - "methods": [ - "get_api" - ] - }, - "GetApiDeployment": { - "methods": [ - "get_api_deployment" - ] - }, - "GetApiSpec": { - "methods": [ - "get_api_spec" - ] - }, - "GetApiSpecContents": { - "methods": [ - "get_api_spec_contents" - ] - }, - "GetApiVersion": { - "methods": [ - "get_api_version" - ] - }, - "GetArtifact": { - "methods": [ - "get_artifact" - ] - }, - "GetArtifactContents": { - "methods": [ - "get_artifact_contents" - ] - }, - "ListApiDeploymentRevisions": { - "methods": [ - "list_api_deployment_revisions" - ] - }, - "ListApiDeployments": { - "methods": [ - "list_api_deployments" - ] - }, - "ListApiSpecRevisions": { - "methods": [ - "list_api_spec_revisions" - ] - }, - "ListApiSpecs": { - "methods": [ - "list_api_specs" - ] - }, - "ListApiVersions": { - "methods": [ - "list_api_versions" - ] - }, - "ListApis": { - "methods": [ - "list_apis" - ] - }, - "ListArtifacts": { - "methods": [ - "list_artifacts" - ] - }, - "ReplaceArtifact": { - "methods": [ - "replace_artifact" - ] - }, - "RollbackApiDeployment": { - "methods": [ - "rollback_api_deployment" - ] - }, - "RollbackApiSpec": { - "methods": [ - "rollback_api_spec" - ] - }, - "TagApiDeploymentRevision": { - "methods": [ - "tag_api_deployment_revision" - ] - }, - "TagApiSpecRevision": { - "methods": [ - "tag_api_spec_revision" - ] - }, - "UpdateApi": { - "methods": [ - "update_api" - ] - }, - "UpdateApiDeployment": { - "methods": [ - "update_api_deployment" - ] - }, - "UpdateApiSpec": { - "methods": [ - "update_api_spec" - ] - }, - "UpdateApiVersion": { - "methods": [ - "update_api_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py deleted file mode 100644 index 405b1ce..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# -__version__ = "0.1.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed deleted file mode 100644 index 4602793..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-apigee-registry package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py deleted file mode 100644 index e8e1c38..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- 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. -# diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py deleted file mode 100644 index 475c17b..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- 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. -# -from .client import ProvisioningClient -from .async_client import ProvisioningAsyncClient - -__all__ = ( - 'ProvisioningClient', - 'ProvisioningAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py deleted file mode 100644 index 5a9da91..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/async_client.py +++ /dev/null @@ -1,1166 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.apigee_registry_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.apigee_registry_v1.types import provisioning_service -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 empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ProvisioningTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import ProvisioningGrpcAsyncIOTransport -from .client import ProvisioningClient - - -class ProvisioningAsyncClient: - """The service that is used for managing the data plane - provisioning of the Registry. - """ - - _client: ProvisioningClient - - DEFAULT_ENDPOINT = ProvisioningClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = ProvisioningClient.DEFAULT_MTLS_ENDPOINT - - instance_path = staticmethod(ProvisioningClient.instance_path) - parse_instance_path = staticmethod(ProvisioningClient.parse_instance_path) - common_billing_account_path = staticmethod(ProvisioningClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(ProvisioningClient.parse_common_billing_account_path) - common_folder_path = staticmethod(ProvisioningClient.common_folder_path) - parse_common_folder_path = staticmethod(ProvisioningClient.parse_common_folder_path) - common_organization_path = staticmethod(ProvisioningClient.common_organization_path) - parse_common_organization_path = staticmethod(ProvisioningClient.parse_common_organization_path) - common_project_path = staticmethod(ProvisioningClient.common_project_path) - parse_common_project_path = staticmethod(ProvisioningClient.parse_common_project_path) - common_location_path = staticmethod(ProvisioningClient.common_location_path) - parse_common_location_path = staticmethod(ProvisioningClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProvisioningAsyncClient: The constructed client. - """ - return ProvisioningClient.from_service_account_info.__func__(ProvisioningAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProvisioningAsyncClient: The constructed client. - """ - return ProvisioningClient.from_service_account_file.__func__(ProvisioningAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - 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 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. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return ProvisioningClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> ProvisioningTransport: - """Returns the transport used by the client instance. - - Returns: - ProvisioningTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(ProvisioningClient).get_transport_class, type(ProvisioningClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, ProvisioningTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the provisioning client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.ProvisioningTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = ProvisioningClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_instance(self, - request: Optional[Union[provisioning_service.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance: Optional[provisioning_service.Instance] = None, - instance_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Provisions instance resources for the Registry. - - .. 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 apigee_registry_v1 - - async def sample_create_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningAsyncClient() - - # Initialize request argument(s) - instance = apigee_registry_v1.Instance() - instance.config.cmek_key_name = "cmek_key_name_value" - - request = apigee_registry_v1.CreateInstanceRequest( - parent="parent_value", - instance_id="instance_id_value", - instance=instance, - ) - - # Make the request - operation = client.create_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateInstanceRequest, dict]]): - The request object. Request message for CreateInstance. - parent (:class:`str`): - Required. Parent resource of the Instance, of the form: - ``projects/*/locations/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - instance (:class:`google.cloud.apigee_registry_v1.types.Instance`): - Required. The Instance. - This corresponds to the ``instance`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - instance_id (:class:`str`): - Required. Identifier to assign to the - Instance. Must be unique within scope of - the parent resource. - - This corresponds to the ``instance_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.apigee_registry_v1.types.Instance` An Instance represents the instance resources of the Registry. - Currently, only one instance is allowed for each - project. - - """ - # 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, instance, instance_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = provisioning_service.CreateInstanceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if instance is not None: - request.instance = instance - if instance_id is not None: - request.instance_id = instance_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_instance, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - provisioning_service.Instance, - metadata_type=provisioning_service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def delete_instance(self, - request: Optional[Union[provisioning_service.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Deletes the Registry instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import apigee_registry_v1 - - async def sample_delete_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteInstanceRequest, dict]]): - The request object. Request message for DeleteInstance. - name (:class:`str`): - Required. The name of the Instance to delete. Format: - ``projects/*/locations/*/instances/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = provisioning_service.DeleteInstanceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_instance, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty_pb2.Empty, - metadata_type=provisioning_service.OperationMetadata, - ) - - # Done; return the response. - return response - - async def get_instance(self, - request: Optional[Union[provisioning_service.GetInstanceRequest, 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]] = (), - ) -> provisioning_service.Instance: - r"""Gets details of a single Instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import apigee_registry_v1 - - async def sample_get_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetInstanceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_instance(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetInstanceRequest, dict]]): - The request object. Request message for GetInstance. - name (:class:`str`): - Required. The name of the Instance to retrieve. Format: - ``projects/*/locations/*/instances/*``. - - 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.apigee_registry_v1.types.Instance: - An Instance represents the instance - resources of the Registry. Currently, - only one instance is allowed for each - project. - - """ - # 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 = provisioning_service.GetInstanceRequest(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_instance, - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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 - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "ProvisioningAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py deleted file mode 100644 index 86ef821..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/client.py +++ /dev/null @@ -1,1365 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.apigee_registry_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.apigee_registry_v1.types import provisioning_service -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 empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import ProvisioningTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import ProvisioningGrpcTransport -from .transports.grpc_asyncio import ProvisioningGrpcAsyncIOTransport -from .transports.rest import ProvisioningRestTransport - - -class ProvisioningClientMeta(type): - """Metaclass for the Provisioning client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[ProvisioningTransport]] - _transport_registry["grpc"] = ProvisioningGrpcTransport - _transport_registry["grpc_asyncio"] = ProvisioningGrpcAsyncIOTransport - _transport_registry["rest"] = ProvisioningRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[ProvisioningTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class ProvisioningClient(metaclass=ProvisioningClientMeta): - """The service that is used for managing the data plane - provisioning of the Registry. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "apigeeregistry.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProvisioningClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProvisioningClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> ProvisioningTransport: - """Returns the transport used by the client instance. - - Returns: - ProvisioningTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def instance_path(project: str,location: str,instance: str,) -> str: - """Returns a fully-qualified instance string.""" - return "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) - - @staticmethod - def parse_instance_path(path: str) -> Dict[str,str]: - """Parses a instance path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - 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 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. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, ProvisioningTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the provisioning client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ProvisioningTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, ProvisioningTransport): - # transport is a ProvisioningTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def create_instance(self, - request: Optional[Union[provisioning_service.CreateInstanceRequest, dict]] = None, - *, - parent: Optional[str] = None, - instance: Optional[provisioning_service.Instance] = None, - instance_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Provisions instance resources for the Registry. - - .. 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 apigee_registry_v1 - - def sample_create_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningClient() - - # Initialize request argument(s) - instance = apigee_registry_v1.Instance() - instance.config.cmek_key_name = "cmek_key_name_value" - - request = apigee_registry_v1.CreateInstanceRequest( - parent="parent_value", - instance_id="instance_id_value", - instance=instance, - ) - - # Make the request - operation = client.create_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.CreateInstanceRequest, dict]): - The request object. Request message for CreateInstance. - parent (str): - Required. Parent resource of the Instance, of the form: - ``projects/*/locations/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - instance (google.cloud.apigee_registry_v1.types.Instance): - Required. The Instance. - This corresponds to the ``instance`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - instance_id (str): - Required. Identifier to assign to the - Instance. Must be unique within scope of - the parent resource. - - This corresponds to the ``instance_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.apigee_registry_v1.types.Instance` An Instance represents the instance resources of the Registry. - Currently, only one instance is allowed for each - project. - - """ - # 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, instance, instance_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a provisioning_service.CreateInstanceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, provisioning_service.CreateInstanceRequest): - request = provisioning_service.CreateInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if instance is not None: - request.instance = instance - if instance_id is not None: - request.instance_id = instance_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_instance] - - # 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, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - provisioning_service.Instance, - metadata_type=provisioning_service.OperationMetadata, - ) - - # Done; return the response. - return response - - def delete_instance(self, - request: Optional[Union[provisioning_service.DeleteInstanceRequest, dict]] = None, - *, - name: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Deletes the Registry instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import apigee_registry_v1 - - def sample_delete_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteInstanceRequest, dict]): - The request object. Request message for DeleteInstance. - name (str): - Required. The name of the Instance to delete. Format: - ``projects/*/locations/*/instances/*``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } - - """ - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a provisioning_service.DeleteInstanceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, provisioning_service.DeleteInstanceRequest): - request = provisioning_service.DeleteInstanceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_instance] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty_pb2.Empty, - metadata_type=provisioning_service.OperationMetadata, - ) - - # Done; return the response. - return response - - def get_instance(self, - request: Optional[Union[provisioning_service.GetInstanceRequest, 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]] = (), - ) -> provisioning_service.Instance: - r"""Gets details of a single Instance. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import apigee_registry_v1 - - def sample_get_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetInstanceRequest( - name="name_value", - ) - - # Make the request - response = client.get_instance(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetInstanceRequest, dict]): - The request object. Request message for GetInstance. - name (str): - Required. The name of the Instance to retrieve. Format: - ``projects/*/locations/*/instances/*``. - - 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.apigee_registry_v1.types.Instance: - An Instance represents the instance - resources of the Registry. Currently, - only one instance is allowed for each - project. - - """ - # 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 provisioning_service.GetInstanceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, provisioning_service.GetInstanceRequest): - request = provisioning_service.GetInstanceRequest(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_instance] - - # 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) -> "ProvisioningClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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__) - - -__all__ = ( - "ProvisioningClient", -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py deleted file mode 100644 index 65fbb49..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import ProvisioningTransport -from .grpc import ProvisioningGrpcTransport -from .grpc_asyncio import ProvisioningGrpcAsyncIOTransport -from .rest import ProvisioningRestTransport -from .rest import ProvisioningRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[ProvisioningTransport]] -_transport_registry['grpc'] = ProvisioningGrpcTransport -_transport_registry['grpc_asyncio'] = ProvisioningGrpcAsyncIOTransport -_transport_registry['rest'] = ProvisioningRestTransport - -__all__ = ( - 'ProvisioningTransport', - 'ProvisioningGrpcTransport', - 'ProvisioningGrpcAsyncIOTransport', - 'ProvisioningRestTransport', - 'ProvisioningRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py deleted file mode 100644 index 3cf016f..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/base.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- 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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.apigee_registry_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.apigee_registry_v1.types import provisioning_service -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.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class ProvisioningTransport(abc.ABC): - """Abstract transport class for Provisioning.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'apigeeregistry.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_instance: gapic_v1.method.wrap_method( - self.create_instance, - default_timeout=None, - client_info=client_info, - ), - self.delete_instance: gapic_v1.method.wrap_method( - self.delete_instance, - default_timeout=None, - client_info=client_info, - ), - self.get_instance: gapic_v1.method.wrap_method( - self.get_instance, - default_timeout=None, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_instance(self) -> Callable[ - [provisioning_service.CreateInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def delete_instance(self) -> Callable[ - [provisioning_service.DeleteInstanceRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_instance(self) -> Callable[ - [provisioning_service.GetInstanceRequest], - Union[ - provisioning_service.Instance, - Awaitable[provisioning_service.Instance] - ]]: - 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 set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - 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() - - -__all__ = ( - 'ProvisioningTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py deleted file mode 100644 index af6ec37..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc.py +++ /dev/null @@ -1,527 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import operations_v1 -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.apigee_registry_v1.types import provisioning_service -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.longrunning import operations_pb2 # type: ignore -from .base import ProvisioningTransport, DEFAULT_CLIENT_INFO - - -class ProvisioningGrpcTransport(ProvisioningTransport): - """gRPC backend transport for Provisioning. - - The service that is used for managing the data plane - provisioning of the Registry. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_instance(self) -> Callable[ - [provisioning_service.CreateInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the create instance method over gRPC. - - Provisions instance resources for the Registry. - - Returns: - Callable[[~.CreateInstanceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_instance' not in self._stubs: - self._stubs['create_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Provisioning/CreateInstance', - request_serializer=provisioning_service.CreateInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_instance'] - - @property - def delete_instance(self) -> Callable[ - [provisioning_service.DeleteInstanceRequest], - operations_pb2.Operation]: - r"""Return a callable for the delete instance method over gRPC. - - Deletes the Registry instance. - - Returns: - Callable[[~.DeleteInstanceRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_instance' not in self._stubs: - self._stubs['delete_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Provisioning/DeleteInstance', - request_serializer=provisioning_service.DeleteInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_instance'] - - @property - def get_instance(self) -> Callable[ - [provisioning_service.GetInstanceRequest], - provisioning_service.Instance]: - r"""Return a callable for the get instance method over gRPC. - - Gets details of a single Instance. - - Returns: - Callable[[~.GetInstanceRequest], - ~.Instance]: - 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_instance' not in self._stubs: - self._stubs['get_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Provisioning/GetInstance', - request_serializer=provisioning_service.GetInstanceRequest.serialize, - response_deserializer=provisioning_service.Instance.deserialize, - ) - return self._stubs['get_instance'] - - 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 set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'ProvisioningGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py deleted file mode 100644 index 0ffd095..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/grpc_asyncio.py +++ /dev/null @@ -1,526 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.apigee_registry_v1.types import provisioning_service -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.longrunning import operations_pb2 # type: ignore -from .base import ProvisioningTransport, DEFAULT_CLIENT_INFO -from .grpc import ProvisioningGrpcTransport - - -class ProvisioningGrpcAsyncIOTransport(ProvisioningTransport): - """gRPC AsyncIO backend transport for Provisioning. - - The service that is used for managing the data plane - provisioning of the Registry. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Quick check: Only create a new client if we do not already have one. - if self._operations_client is None: - self._operations_client = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self._operations_client - - @property - def create_instance(self) -> Callable[ - [provisioning_service.CreateInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create instance method over gRPC. - - Provisions instance resources for the Registry. - - Returns: - Callable[[~.CreateInstanceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_instance' not in self._stubs: - self._stubs['create_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Provisioning/CreateInstance', - request_serializer=provisioning_service.CreateInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_instance'] - - @property - def delete_instance(self) -> Callable[ - [provisioning_service.DeleteInstanceRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the delete instance method over gRPC. - - Deletes the Registry instance. - - Returns: - Callable[[~.DeleteInstanceRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_instance' not in self._stubs: - self._stubs['delete_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Provisioning/DeleteInstance', - request_serializer=provisioning_service.DeleteInstanceRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['delete_instance'] - - @property - def get_instance(self) -> Callable[ - [provisioning_service.GetInstanceRequest], - Awaitable[provisioning_service.Instance]]: - r"""Return a callable for the get instance method over gRPC. - - Gets details of a single Instance. - - Returns: - Callable[[~.GetInstanceRequest], - Awaitable[~.Instance]]: - 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_instance' not in self._stubs: - self._stubs['get_instance'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Provisioning/GetInstance', - request_serializer=provisioning_service.GetInstanceRequest.serialize, - response_deserializer=provisioning_service.Instance.deserialize, - ) - return self._stubs['get_instance'] - - 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"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'ProvisioningGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py deleted file mode 100644 index f796320..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/provisioning/transports/rest.py +++ /dev/null @@ -1,1470 +0,0 @@ -# -*- 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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.cloud.apigee_registry_v1.types import provisioning_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import ProvisioningTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class ProvisioningRestInterceptor: - """Interceptor for Provisioning. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the ProvisioningRestTransport. - - .. code-block:: python - class MyCustomProvisioningInterceptor(ProvisioningRestInterceptor): - def pre_create_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_instance(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_instance(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_instance(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_instance(self, response): - logging.log(f"Received response: {response}") - return response - - transport = ProvisioningRestTransport(interceptor=MyCustomProvisioningInterceptor()) - client = ProvisioningClient(transport=transport) - - - """ - def pre_create_instance(self, request: provisioning_service.CreateInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[provisioning_service.CreateInstanceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_create_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_instance - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_delete_instance(self, request: provisioning_service.DeleteInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[provisioning_service.DeleteInstanceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_delete_instance(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_instance - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_get_instance(self, request: provisioning_service.GetInstanceRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[provisioning_service.GetInstanceRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_instance - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_get_instance(self, response: provisioning_service.Instance) -> provisioning_service.Instance: - """Post-rpc interceptor for get_instance - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Provisioning server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Provisioning server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class ProvisioningRestStub: - _session: AuthorizedSession - _host: str - _interceptor: ProvisioningRestInterceptor - - -class ProvisioningRestTransport(ProvisioningTransport): - """REST backend transport for Provisioning. - - The service that is used for managing the data plane - provisioning of the Registry. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[ProvisioningRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or ProvisioningRestInterceptor() - self._prep_wrapped_messages(client_info) - - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - 'google.longrunning.Operations.CancelOperation': [ - { - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ], - 'google.longrunning.Operations.DeleteOperation': [ - { - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ], - 'google.longrunning.Operations.ListOperations': [ - { - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ], - } - - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1") - - self._operations_client = operations_v1.AbstractOperationsClient(transport=rest_transport) - - # Return the client from cache. - return self._operations_client - - class _CreateInstance(ProvisioningRestStub): - def __hash__(self): - return hash("CreateInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "instanceId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: provisioning_service.CreateInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create instance method over HTTP. - - Args: - request (~.provisioning_service.CreateInstanceRequest): - The request object. Request message for CreateInstance. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/instances', - 'body': 'instance', - }, - ] - request, metadata = self._interceptor.pre_create_instance(request, metadata) - pb_request = provisioning_service.CreateInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_instance(resp) - return resp - - class _DeleteInstance(ProvisioningRestStub): - def __hash__(self): - return hash("DeleteInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: provisioning_service.DeleteInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the delete instance method over HTTP. - - Args: - request (~.provisioning_service.DeleteInstanceRequest): - The request object. Request message for DeleteInstance. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/instances/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_instance(request, metadata) - pb_request = provisioning_service.DeleteInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_instance(resp) - return resp - - class _GetInstance(ProvisioningRestStub): - def __hash__(self): - return hash("GetInstance") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: provisioning_service.GetInstanceRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> provisioning_service.Instance: - r"""Call the get instance method over HTTP. - - Args: - request (~.provisioning_service.GetInstanceRequest): - The request object. Request message for GetInstance. - 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: - ~.provisioning_service.Instance: - An Instance represents the instance - resources of the Registry. Currently, - only one instance is allowed for each - project. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/instances/*}', - }, - ] - request, metadata = self._interceptor.pre_get_instance(request, metadata) - pb_request = provisioning_service.GetInstanceRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = provisioning_service.Instance() - pb_resp = provisioning_service.Instance.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_instance(resp) - return resp - - @property - def create_instance(self) -> Callable[ - [provisioning_service.CreateInstanceRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_instance(self) -> Callable[ - [provisioning_service.DeleteInstanceRequest], - operations_pb2.Operation]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_instance(self) -> Callable[ - [provisioning_service.GetInstanceRequest], - provisioning_service.Instance]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetInstance(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(ProvisioningRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(ProvisioningRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(ProvisioningRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/runtime}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(ProvisioningRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/runtime}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.loads(json.dumps(transcoded_request['body'])) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(ProvisioningRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/runtime}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.loads(json.dumps(transcoded_request['body'])) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(ProvisioningRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.loads(json.dumps(transcoded_request['body'])) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(ProvisioningRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(ProvisioningRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object 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: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(ProvisioningRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object 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 from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'ProvisioningRestTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py deleted file mode 100644 index d21b3d3..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- 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. -# -from .client import RegistryClient -from .async_client import RegistryAsyncClient - -__all__ = ( - 'RegistryClient', - 'RegistryAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py deleted file mode 100644 index 80509c2..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/async_client.py +++ /dev/null @@ -1,4984 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.apigee_registry_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.apigee_registry_v1.services.registry import pagers -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service -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 any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import RegistryTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import RegistryGrpcAsyncIOTransport -from .client import RegistryClient - - -class RegistryAsyncClient: - """The Registry service allows teams to manage descriptions of - APIs. - """ - - _client: RegistryClient - - DEFAULT_ENDPOINT = RegistryClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = RegistryClient.DEFAULT_MTLS_ENDPOINT - - api_path = staticmethod(RegistryClient.api_path) - parse_api_path = staticmethod(RegistryClient.parse_api_path) - api_deployment_path = staticmethod(RegistryClient.api_deployment_path) - parse_api_deployment_path = staticmethod(RegistryClient.parse_api_deployment_path) - api_spec_path = staticmethod(RegistryClient.api_spec_path) - parse_api_spec_path = staticmethod(RegistryClient.parse_api_spec_path) - api_version_path = staticmethod(RegistryClient.api_version_path) - parse_api_version_path = staticmethod(RegistryClient.parse_api_version_path) - artifact_path = staticmethod(RegistryClient.artifact_path) - parse_artifact_path = staticmethod(RegistryClient.parse_artifact_path) - common_billing_account_path = staticmethod(RegistryClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(RegistryClient.parse_common_billing_account_path) - common_folder_path = staticmethod(RegistryClient.common_folder_path) - parse_common_folder_path = staticmethod(RegistryClient.parse_common_folder_path) - common_organization_path = staticmethod(RegistryClient.common_organization_path) - parse_common_organization_path = staticmethod(RegistryClient.parse_common_organization_path) - common_project_path = staticmethod(RegistryClient.common_project_path) - parse_common_project_path = staticmethod(RegistryClient.parse_common_project_path) - common_location_path = staticmethod(RegistryClient.common_location_path) - parse_common_location_path = staticmethod(RegistryClient.parse_common_location_path) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegistryAsyncClient: The constructed client. - """ - return RegistryClient.from_service_account_info.__func__(RegistryAsyncClient, info, *args, **kwargs) # type: ignore - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegistryAsyncClient: The constructed client. - """ - return RegistryClient.from_service_account_file.__func__(RegistryAsyncClient, filename, *args, **kwargs) # type: ignore - - from_service_account_json = from_service_account_file - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - 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 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. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - return RegistryClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> RegistryTransport: - """Returns the transport used by the client instance. - - Returns: - RegistryTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(RegistryClient).get_transport_class, type(RegistryClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, RegistryTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the registry client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.RegistryTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = RegistryClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_apis(self, - request: Optional[Union[registry_service.ListApisRequest, 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.ListApisAsyncPager: - r"""Returns matching APIs. - - .. 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 apigee_registry_v1 - - async def sample_list_apis(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApisRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_apis(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApisRequest, dict]]): - The request object. Request message for ListApis. - parent (:class:`str`): - Required. The parent, which owns this collection of - APIs. Format: ``projects/*/locations/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApisAsyncPager: - Response message for ListApis. - 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 = registry_service.ListApisRequest(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_apis, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListApisAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_api(self, - request: Optional[Union[registry_service.GetApiRequest, 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]] = (), - ) -> registry_models.Api: - r"""Returns a specified API. - - .. 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 apigee_registry_v1 - - async def sample_get_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiRequest, dict]]): - The request object. Request message for GetApi. - name (:class:`str`): - Required. The name of the API to retrieve. Format: - ``projects/*/locations/*/apis/*`` - - 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.apigee_registry_v1.types.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - # 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 = registry_service.GetApiRequest(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_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_api(self, - request: Optional[Union[registry_service.CreateApiRequest, dict]] = None, - *, - parent: Optional[str] = None, - api: Optional[registry_models.Api] = None, - api_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Api: - r"""Creates a specified API. - - .. 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 apigee_registry_v1 - - async def sample_create_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiRequest( - parent="parent_value", - api_id="api_id_value", - ) - - # Make the request - response = await client.create_api(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiRequest, dict]]): - The request object. Request message for CreateApi. - parent (:class:`str`): - Required. The parent, which owns this collection of - APIs. Format: ``projects/*/locations/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api (:class:`google.cloud.apigee_registry_v1.types.Api`): - Required. The API to create. - This corresponds to the ``api`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_id (:class:`str`): - Required. The ID to use for the API, which will become - the final component of the API's resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - # 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, api, api_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.CreateApiRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api is not None: - request.api = api - if api_id is not None: - request.api_id = api_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_api(self, - request: Optional[Union[registry_service.UpdateApiRequest, dict]] = None, - *, - api: Optional[registry_models.Api] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Api: - r"""Used to modify a specified API. - - .. 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 apigee_registry_v1 - - async def sample_update_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiRequest( - ) - - # Make the request - response = await client.update_api(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiRequest, dict]]): - The request object. Request message for UpdateApi. - api (:class:`google.cloud.apigee_registry_v1.types.Api`): - Required. The API to update. - - The ``name`` field is used to identify the API to - update. Format: ``projects/*/locations/*/apis/*`` - - This corresponds to the ``api`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - # 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([api, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.UpdateApiRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api is not None: - request.api = api - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api.name", request.api.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_api(self, - request: Optional[Union[registry_service.DeleteApiRequest, 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]] = (), - ) -> None: - r"""Removes a specified API and all of the resources that - it owns. - - .. 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 apigee_registry_v1 - - async def sample_delete_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiRequest( - name="name_value", - ) - - # Make the request - await client.delete_api(request=request) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiRequest, dict]]): - The request object. Request message for DeleteApi. - name (:class:`str`): - Required. The name of the API to delete. Format: - ``projects/*/locations/*/apis/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = registry_service.DeleteApiRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_api_versions(self, - request: Optional[Union[registry_service.ListApiVersionsRequest, 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.ListApiVersionsAsyncPager: - r"""Returns matching versions. - - .. 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 apigee_registry_v1 - - async def sample_list_api_versions(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiVersionsRequest, dict]]): - The request object. Request message for ListApiVersions. - parent (:class:`str`): - Required. The parent, which owns this collection of - versions. Format: ``projects/*/locations/*/apis/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApiVersionsAsyncPager: - Response message for ListApiVersions. - 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 = registry_service.ListApiVersionsRequest(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_api_versions, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListApiVersionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_api_version(self, - request: Optional[Union[registry_service.GetApiVersionRequest, 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]] = (), - ) -> registry_models.ApiVersion: - r"""Returns a specified version. - - .. 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 apigee_registry_v1 - - async def sample_get_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiVersionRequest, dict]]): - The request object. Request message for GetApiVersion. - name (:class:`str`): - Required. The name of the version to retrieve. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - 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.apigee_registry_v1.types.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - # 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 = registry_service.GetApiVersionRequest(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_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_api_version(self, - request: Optional[Union[registry_service.CreateApiVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - api_version: Optional[registry_models.ApiVersion] = None, - api_version_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiVersion: - r"""Creates a specified version. - - .. 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 apigee_registry_v1 - - async def sample_create_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiVersionRequest( - parent="parent_value", - api_version_id="api_version_id_value", - ) - - # Make the request - response = await client.create_api_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiVersionRequest, dict]]): - The request object. Request message for - CreateApiVersion. - parent (:class:`str`): - Required. The parent, which owns this collection of - versions. Format: ``projects/*/locations/*/apis/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_version (:class:`google.cloud.apigee_registry_v1.types.ApiVersion`): - Required. The version to create. - This corresponds to the ``api_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_version_id (:class:`str`): - Required. The ID to use for the version, which will - become the final component of the version's resource - name. - - This value should be 1-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_version_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - # 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, api_version, api_version_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.CreateApiVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api_version is not None: - request.api_version = api_version - if api_version_id is not None: - request.api_version_id = api_version_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_api_version(self, - request: Optional[Union[registry_service.UpdateApiVersionRequest, dict]] = None, - *, - api_version: Optional[registry_models.ApiVersion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiVersion: - r"""Used to modify a specified version. - - .. 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 apigee_registry_v1 - - async def sample_update_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiVersionRequest( - ) - - # Make the request - response = await client.update_api_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest, dict]]): - The request object. Request message for - UpdateApiVersion. - api_version (:class:`google.cloud.apigee_registry_v1.types.ApiVersion`): - Required. The version to update. - - The ``name`` field is used to identify the version to - update. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - This corresponds to the ``api_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - # 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([api_version, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.UpdateApiVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api_version is not None: - request.api_version = api_version - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api_version.name", request.api_version.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_api_version(self, - request: Optional[Union[registry_service.DeleteApiVersionRequest, 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]] = (), - ) -> None: - r"""Removes a specified version and all of the resources - that it owns. - - .. 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 apigee_registry_v1 - - async def sample_delete_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiVersionRequest( - name="name_value", - ) - - # Make the request - await client.delete_api_version(request=request) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest, dict]]): - The request object. Request message for - DeleteApiVersion. - name (:class:`str`): - Required. The name of the version to delete. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = registry_service.DeleteApiVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def list_api_specs(self, - request: Optional[Union[registry_service.ListApiSpecsRequest, 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.ListApiSpecsAsyncPager: - r"""Returns matching specs. - - .. 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 apigee_registry_v1 - - async def sample_list_api_specs(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_specs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiSpecsRequest, dict]]): - The request object. Request message for ListApiSpecs. - parent (:class:`str`): - Required. The parent, which owns this collection of - specs. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApiSpecsAsyncPager: - Response message for ListApiSpecs. - 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 = registry_service.ListApiSpecsRequest(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_api_specs, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListApiSpecsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_api_spec(self, - request: Optional[Union[registry_service.GetApiSpecRequest, 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]] = (), - ) -> registry_models.ApiSpec: - r"""Returns a specified spec. - - .. 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 apigee_registry_v1 - - async def sample_get_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiSpecRequest, dict]]): - The request object. Request message for GetApiSpec. - name (:class:`str`): - Required. The name of the spec to retrieve. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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 = registry_service.GetApiSpecRequest(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_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("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_api_spec_contents(self, - request: Optional[Union[registry_service.GetApiSpecContentsRequest, 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]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Returns the contents of a specified spec. If specs are stored - with GZip compression, the default behavior is to return the - spec uncompressed (the mime_type response field indicates the - exact format returned). - - .. 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 apigee_registry_v1 - - async def sample_get_api_spec_contents(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecContentsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_spec_contents(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest, dict]]): - The request object. Request message for - GetApiSpecContents. - name (:class:`str`): - Required. The name of the spec whose contents should be - retrieved. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # 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 = registry_service.GetApiSpecContentsRequest(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_api_spec_contents, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_api_spec(self, - request: Optional[Union[registry_service.CreateApiSpecRequest, dict]] = None, - *, - parent: Optional[str] = None, - api_spec: Optional[registry_models.ApiSpec] = None, - api_spec_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Creates a specified spec. - - .. 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 apigee_registry_v1 - - async def sample_create_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiSpecRequest( - parent="parent_value", - api_spec_id="api_spec_id_value", - ) - - # Make the request - response = await client.create_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiSpecRequest, dict]]): - The request object. Request message for CreateApiSpec. - parent (:class:`str`): - Required. The parent, which owns this collection of - specs. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_spec (:class:`google.cloud.apigee_registry_v1.types.ApiSpec`): - Required. The spec to create. - This corresponds to the ``api_spec`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_spec_id (:class:`str`): - Required. The ID to use for the spec, which will become - the final component of the spec's resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_spec_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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, api_spec, api_spec_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.CreateApiSpecRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api_spec is not None: - request.api_spec = api_spec - if api_spec_id is not None: - request.api_spec_id = api_spec_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_api_spec(self, - request: Optional[Union[registry_service.UpdateApiSpecRequest, dict]] = None, - *, - api_spec: Optional[registry_models.ApiSpec] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Used to modify a specified spec. - - .. 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 apigee_registry_v1 - - async def sample_update_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiSpecRequest( - ) - - # Make the request - response = await client.update_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest, dict]]): - The request object. Request message for UpdateApiSpec. - api_spec (:class:`google.cloud.apigee_registry_v1.types.ApiSpec`): - Required. The spec to update. - - The ``name`` field is used to identify the spec to - update. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - This corresponds to the ``api_spec`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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([api_spec, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.UpdateApiSpecRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api_spec is not None: - request.api_spec = api_spec - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api_spec.name", request.api_spec.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_api_spec(self, - request: Optional[Union[registry_service.DeleteApiSpecRequest, 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]] = (), - ) -> None: - r"""Removes a specified spec, all revisions, and all - child resources (e.g., artifacts). - - .. 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 apigee_registry_v1 - - async def sample_delete_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRequest( - name="name_value", - ) - - # Make the request - await client.delete_api_spec(request=request) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest, dict]]): - The request object. Request message for DeleteApiSpec. - name (:class:`str`): - Required. The name of the spec to delete. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = registry_service.DeleteApiSpecRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def tag_api_spec_revision(self, - request: Optional[Union[registry_service.TagApiSpecRevisionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Adds a tag to a specified revision of a spec. - - .. 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 apigee_registry_v1 - - async def sample_tag_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiSpecRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = await client.tag_api_spec_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest, dict]]): - The request object. Request message for - TagApiSpecRevision. - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # Create or coerce a protobuf request object. - request = registry_service.TagApiSpecRevisionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.tag_api_spec_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("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_api_spec_revisions(self, - request: Optional[Union[registry_service.ListApiSpecRevisionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListApiSpecRevisionsAsyncPager: - r"""Lists all revisions of a spec. - Revisions are returned in descending order of revision - creation time. - - .. 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 apigee_registry_v1 - - async def sample_list_api_spec_revisions(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_spec_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest, dict]]): - The request object. Request message for - ListApiSpecRevisions. - 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.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsAsyncPager: - Response message for - ListApiSpecRevisionsResponse. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = registry_service.ListApiSpecRevisionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_api_spec_revisions, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListApiSpecRevisionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def rollback_api_spec(self, - request: Optional[Union[registry_service.RollbackApiSpecRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - .. 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 apigee_registry_v1 - - async def sample_rollback_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiSpecRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = await client.rollback_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest, dict]]): - The request object. Request message for RollbackApiSpec. - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # Create or coerce a protobuf request object. - request = registry_service.RollbackApiSpecRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.rollback_api_spec, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_api_spec_revision(self, - request: Optional[Union[registry_service.DeleteApiSpecRevisionRequest, 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]] = (), - ) -> registry_models.ApiSpec: - r"""Deletes a revision of a spec. - - .. 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 apigee_registry_v1 - - async def sample_delete_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.delete_api_spec_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest, dict]]): - The request object. Request message for - DeleteApiSpecRevision. - name (:class:`str`): - Required. The name of the spec revision to be deleted, - with a revision ID explicitly included. - - Example: - ``projects/sample/locations/global/apis/petstore/versions/1.0.0/specs/openapi.yaml@c7cfa2a8`` - - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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 = registry_service.DeleteApiSpecRevisionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_api_spec_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("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_api_deployments(self, - request: Optional[Union[registry_service.ListApiDeploymentsRequest, 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.ListApiDeploymentsAsyncPager: - r"""Returns matching deployments. - - .. 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 apigee_registry_v1 - - async def sample_list_api_deployments(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_deployments(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest, dict]]): - The request object. Request message for - ListApiDeployments. - parent (:class:`str`): - Required. The parent, which owns this collection of - deployments. Format: ``projects/*/locations/*/apis/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsAsyncPager: - Response message for - ListApiDeployments. - 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 = registry_service.ListApiDeploymentsRequest(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_api_deployments, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListApiDeploymentsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_api_deployment(self, - request: Optional[Union[registry_service.GetApiDeploymentRequest, 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]] = (), - ) -> registry_models.ApiDeployment: - r"""Returns a specified deployment. - - .. 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 apigee_registry_v1 - - async def sample_get_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiDeploymentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest, dict]]): - The request object. Request message for - GetApiDeployment. - name (:class:`str`): - Required. The name of the deployment to retrieve. - Format: ``projects/*/locations/*/apis/*/deployments/*`` - - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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 = registry_service.GetApiDeploymentRequest(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_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_api_deployment(self, - request: Optional[Union[registry_service.CreateApiDeploymentRequest, dict]] = None, - *, - parent: Optional[str] = None, - api_deployment: Optional[registry_models.ApiDeployment] = None, - api_deployment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Creates a specified deployment. - - .. 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 apigee_registry_v1 - - async def sample_create_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiDeploymentRequest( - parent="parent_value", - api_deployment_id="api_deployment_id_value", - ) - - # Make the request - response = await client.create_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest, dict]]): - The request object. Request message for - CreateApiDeployment. - parent (:class:`str`): - Required. The parent, which owns this collection of - deployments. Format: ``projects/*/locations/*/apis/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_deployment (:class:`google.cloud.apigee_registry_v1.types.ApiDeployment`): - Required. The deployment to create. - This corresponds to the ``api_deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_deployment_id (:class:`str`): - Required. The ID to use for the deployment, which will - become the final component of the deployment's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_deployment_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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, api_deployment, api_deployment_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.CreateApiDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api_deployment is not None: - request.api_deployment = api_deployment - if api_deployment_id is not None: - request.api_deployment_id = api_deployment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_api_deployment(self, - request: Optional[Union[registry_service.UpdateApiDeploymentRequest, dict]] = None, - *, - api_deployment: Optional[registry_models.ApiDeployment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Used to modify a specified deployment. - - .. 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 apigee_registry_v1 - - async def sample_update_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiDeploymentRequest( - ) - - # Make the request - response = await client.update_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest, dict]]): - The request object. Request message for - UpdateApiDeployment. - api_deployment (:class:`google.cloud.apigee_registry_v1.types.ApiDeployment`): - Required. The deployment to update. - - The ``name`` field is used to identify the deployment to - update. Format: - ``projects/*/locations/*/apis/*/deployments/*`` - - This corresponds to the ``api_deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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([api_deployment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.UpdateApiDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api_deployment is not None: - request.api_deployment = api_deployment - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api_deployment.name", request.api_deployment.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_api_deployment(self, - request: Optional[Union[registry_service.DeleteApiDeploymentRequest, 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]] = (), - ) -> None: - r"""Removes a specified deployment, all revisions, and - all child resources (e.g., artifacts). - - .. 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 apigee_registry_v1 - - async def sample_delete_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRequest( - name="name_value", - ) - - # Make the request - await client.delete_api_deployment(request=request) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest, dict]]): - The request object. Request message for - DeleteApiDeployment. - name (:class:`str`): - Required. The name of the deployment to delete. Format: - ``projects/*/locations/*/apis/*/deployments/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = registry_service.DeleteApiDeploymentRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - async def tag_api_deployment_revision(self, - request: Optional[Union[registry_service.TagApiDeploymentRevisionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Adds a tag to a specified revision of a - deployment. - - .. 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 apigee_registry_v1 - - async def sample_tag_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiDeploymentRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = await client.tag_api_deployment_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest, dict]]): - The request object. Request message for - TagApiDeploymentRevision. - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # Create or coerce a protobuf request object. - request = registry_service.TagApiDeploymentRevisionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.tag_api_deployment_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("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_api_deployment_revisions(self, - request: Optional[Union[registry_service.ListApiDeploymentRevisionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListApiDeploymentRevisionsAsyncPager: - r"""Lists all revisions of a deployment. - Revisions are returned in descending order of revision - creation time. - - .. 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 apigee_registry_v1 - - async def sample_list_api_deployment_revisions(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_deployment_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest, dict]]): - The request object. Request message for - ListApiDeploymentRevisions. - 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsAsyncPager: - Response message for - ListApiDeploymentRevisionsResponse. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - request = registry_service.ListApiDeploymentRevisionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_api_deployment_revisions, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListApiDeploymentRevisionsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def rollback_api_deployment(self, - request: Optional[Union[registry_service.RollbackApiDeploymentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - .. 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 apigee_registry_v1 - - async def sample_rollback_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiDeploymentRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = await client.rollback_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest, dict]]): - The request object. Request message for - RollbackApiDeployment. - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # Create or coerce a protobuf request object. - request = registry_service.RollbackApiDeploymentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.rollback_api_deployment, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_api_deployment_revision(self, - request: Optional[Union[registry_service.DeleteApiDeploymentRevisionRequest, 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]] = (), - ) -> registry_models.ApiDeployment: - r"""Deletes a revision of a deployment. - - .. 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 apigee_registry_v1 - - async def sample_delete_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.delete_api_deployment_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest, dict]]): - The request object. Request message for - DeleteApiDeploymentRevision. - name (:class:`str`): - Required. The name of the deployment revision to be - deleted, with a revision ID explicitly included. - - Example: - ``projects/sample/locations/global/apis/petstore/deployments/prod@c7cfa2a8`` - - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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 = registry_service.DeleteApiDeploymentRevisionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_api_deployment_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("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_artifacts(self, - request: Optional[Union[registry_service.ListArtifactsRequest, 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.ListArtifactsAsyncPager: - r"""Returns matching artifacts. - - .. 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 apigee_registry_v1 - - async def sample_list_artifacts(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListArtifactsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_artifacts(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ListArtifactsRequest, dict]]): - The request object. Request message for ListArtifacts. - parent (:class:`str`): - Required. The parent, which owns this collection of - artifacts. Format: ``{parent}`` - - 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.apigee_registry_v1.services.registry.pagers.ListArtifactsAsyncPager: - Response message for ListArtifacts. - 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 = registry_service.ListArtifactsRequest(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_artifacts, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListArtifactsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_artifact(self, - request: Optional[Union[registry_service.GetArtifactRequest, 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]] = (), - ) -> registry_models.Artifact: - r"""Returns a specified artifact. - - .. 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 apigee_registry_v1 - - async def sample_get_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactRequest( - name="name_value", - ) - - # Make the request - response = await client.get_artifact(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetArtifactRequest, dict]]): - The request object. Request message for GetArtifact. - name (:class:`str`): - Required. The name of the artifact to retrieve. Format: - ``{parent}/artifacts/*`` - - 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.apigee_registry_v1.types.Artifact: - Artifacts of resources. Artifacts are unique (single-value) per resource - and are used to store metadata that is too large or - numerous to be stored directly on the resource. Since - artifacts are stored separately from parent - resources, they should generally be used for metadata - that is needed infrequently, i.e., not for display in - primary views of the resource but perhaps displayed - or downloaded upon request. The ListArtifacts method - allows artifacts to be quickly enumerated and checked - for presence without downloading their - (potentially-large) contents. - - """ - # 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 = registry_service.GetArtifactRequest(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_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("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_artifact_contents(self, - request: Optional[Union[registry_service.GetArtifactContentsRequest, 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]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Returns the contents of a specified artifact. If artifacts are - stored with GZip compression, the default behavior is to return - the artifact uncompressed (the mime_type response field - indicates the exact format returned). - - .. 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 apigee_registry_v1 - - async def sample_get_artifact_contents(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactContentsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_artifact_contents(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest, dict]]): - The request object. Request message for - GetArtifactContents. - name (:class:`str`): - Required. The name of the artifact whose contents should - be retrieved. Format: ``{parent}/artifacts/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # 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 = registry_service.GetArtifactContentsRequest(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_artifact_contents, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_artifact(self, - request: Optional[Union[registry_service.CreateArtifactRequest, dict]] = None, - *, - parent: Optional[str] = None, - artifact: Optional[registry_models.Artifact] = None, - artifact_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Artifact: - r"""Creates a specified artifact. - - .. 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 apigee_registry_v1 - - async def sample_create_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateArtifactRequest( - parent="parent_value", - artifact_id="artifact_id_value", - ) - - # Make the request - response = await client.create_artifact(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.CreateArtifactRequest, dict]]): - The request object. Request message for CreateArtifact. - parent (:class:`str`): - Required. The parent, which owns this collection of - artifacts. Format: ``{parent}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - artifact (:class:`google.cloud.apigee_registry_v1.types.Artifact`): - Required. The artifact to create. - This corresponds to the ``artifact`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - artifact_id (:class:`str`): - Required. The ID to use for the artifact, which will - become the final component of the artifact's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``artifact_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.Artifact: - Artifacts of resources. Artifacts are unique (single-value) per resource - and are used to store metadata that is too large or - numerous to be stored directly on the resource. Since - artifacts are stored separately from parent - resources, they should generally be used for metadata - that is needed infrequently, i.e., not for display in - primary views of the resource but perhaps displayed - or downloaded upon request. The ListArtifacts method - allows artifacts to be quickly enumerated and checked - for presence without downloading their - (potentially-large) contents. - - """ - # 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, artifact, artifact_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - request = registry_service.CreateArtifactRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if artifact is not None: - request.artifact = artifact - if artifact_id is not None: - request.artifact_id = artifact_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def replace_artifact(self, - request: Optional[Union[registry_service.ReplaceArtifactRequest, dict]] = None, - *, - artifact: Optional[registry_models.Artifact] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Artifact: - r"""Used to replace a specified artifact. - - .. 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 apigee_registry_v1 - - async def sample_replace_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ReplaceArtifactRequest( - ) - - # Make the request - response = await client.replace_artifact(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest, dict]]): - The request object. Request message for ReplaceArtifact. - artifact (:class:`google.cloud.apigee_registry_v1.types.Artifact`): - Required. The artifact to replace. - - The ``name`` field is used to identify the artifact to - replace. Format: ``{parent}/artifacts/*`` - - This corresponds to the ``artifact`` 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.apigee_registry_v1.types.Artifact: - Artifacts of resources. Artifacts are unique (single-value) per resource - and are used to store metadata that is too large or - numerous to be stored directly on the resource. Since - artifacts are stored separately from parent - resources, they should generally be used for metadata - that is needed infrequently, i.e., not for display in - primary views of the resource but perhaps displayed - or downloaded upon request. The ListArtifacts method - allows artifacts to be quickly enumerated and checked - for presence without downloading their - (potentially-large) contents. - - """ - # 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([artifact]) - 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 = registry_service.ReplaceArtifactRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if artifact is not None: - request.artifact = artifact - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.replace_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("artifact.name", request.artifact.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_artifact(self, - request: Optional[Union[registry_service.DeleteArtifactRequest, 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]] = (), - ) -> None: - r"""Removes a specified artifact. - - .. 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 apigee_registry_v1 - - async def sample_delete_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteArtifactRequest( - name="name_value", - ) - - # Make the request - await client.delete_artifact(request=request) - - Args: - request (Optional[Union[google.cloud.apigee_registry_v1.types.DeleteArtifactRequest, dict]]): - The request object. Request message for DeleteArtifact. - name (:class:`str`): - Required. The name of the artifact to delete. Format: - ``{parent}/artifacts/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 = registry_service.DeleteArtifactRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**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_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._client._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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 - - async def __aexit__(self, exc_type, exc, tb): - await self.transport.close() - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "RegistryAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py deleted file mode 100644 index c6ad584..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/client.py +++ /dev/null @@ -1,4928 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.apigee_registry_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.apigee_registry_v1.services.registry import pagers -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service -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 any_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import RegistryTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import RegistryGrpcTransport -from .transports.grpc_asyncio import RegistryGrpcAsyncIOTransport -from .transports.rest import RegistryRestTransport - - -class RegistryClientMeta(type): - """Metaclass for the Registry client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - _transport_registry = OrderedDict() # type: Dict[str, Type[RegistryTransport]] - _transport_registry["grpc"] = RegistryGrpcTransport - _transport_registry["grpc_asyncio"] = RegistryGrpcAsyncIOTransport - _transport_registry["rest"] = RegistryRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[RegistryTransport]: - """Returns an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class RegistryClient(metaclass=RegistryClientMeta): - """The Registry service allows teams to manage descriptions of - APIs. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "apigeeregistry.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegistryClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_info(info) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - RegistryClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file( - filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> RegistryTransport: - """Returns the transport used by the client instance. - - Returns: - RegistryTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def api_path(project: str,location: str,api: str,) -> str: - """Returns a fully-qualified api string.""" - return "projects/{project}/locations/{location}/apis/{api}".format(project=project, location=location, api=api, ) - - @staticmethod - def parse_api_path(path: str) -> Dict[str,str]: - """Parses a api path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def api_deployment_path(project: str,location: str,api: str,deployment: str,) -> str: - """Returns a fully-qualified api_deployment string.""" - return "projects/{project}/locations/{location}/apis/{api}/deployments/{deployment}".format(project=project, location=location, api=api, deployment=deployment, ) - - @staticmethod - def parse_api_deployment_path(path: str) -> Dict[str,str]: - """Parses a api_deployment path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)/deployments/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def api_spec_path(project: str,location: str,api: str,version: str,spec: str,) -> str: - """Returns a fully-qualified api_spec string.""" - return "projects/{project}/locations/{location}/apis/{api}/versions/{version}/specs/{spec}".format(project=project, location=location, api=api, version=version, spec=spec, ) - - @staticmethod - def parse_api_spec_path(path: str) -> Dict[str,str]: - """Parses a api_spec path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)/versions/(?P.+?)/specs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def api_version_path(project: str,location: str,api: str,version: str,) -> str: - """Returns a fully-qualified api_version string.""" - return "projects/{project}/locations/{location}/apis/{api}/versions/{version}".format(project=project, location=location, api=api, version=version, ) - - @staticmethod - def parse_api_version_path(path: str) -> Dict[str,str]: - """Parses a api_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/apis/(?P.+?)/versions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def artifact_path(project: str,location: str,artifact: str,) -> str: - """Returns a fully-qualified artifact string.""" - return "projects/{project}/locations/{location}/artifacts/{artifact}".format(project=project, location=location, artifact=artifact, ) - - @staticmethod - def parse_artifact_path(path: str) -> Dict[str,str]: - """Parses a artifact path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/artifacts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - 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 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. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, RegistryTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the registry client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, RegistryTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - if client_options is None: - client_options = client_options_lib.ClientOptions() - client_options = cast(client_options_lib.ClientOptions, client_options) - - api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(client_options) - - api_key_value = getattr(client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, RegistryTransport): - # transport is a RegistryTransport instance. - if credentials or client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = transport - else: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - client_cert_source_for_mtls=client_cert_source_func, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=client_options.api_audience, - ) - - def list_apis(self, - request: Optional[Union[registry_service.ListApisRequest, 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.ListApisPager: - r"""Returns matching APIs. - - .. 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 apigee_registry_v1 - - def sample_list_apis(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApisRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_apis(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ListApisRequest, dict]): - The request object. Request message for ListApis. - parent (str): - Required. The parent, which owns this collection of - APIs. Format: ``projects/*/locations/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApisPager: - Response message for ListApis. - 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 registry_service.ListApisRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ListApisRequest): - request = registry_service.ListApisRequest(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_apis] - - # 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.ListApisPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_api(self, - request: Optional[Union[registry_service.GetApiRequest, 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]] = (), - ) -> registry_models.Api: - r"""Returns a specified API. - - .. 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 apigee_registry_v1 - - def sample_get_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiRequest( - name="name_value", - ) - - # Make the request - response = client.get_api(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetApiRequest, dict]): - The request object. Request message for GetApi. - name (str): - Required. The name of the API to retrieve. Format: - ``projects/*/locations/*/apis/*`` - - 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.apigee_registry_v1.types.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - # 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 registry_service.GetApiRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.GetApiRequest): - request = registry_service.GetApiRequest(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_api] - - # 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 create_api(self, - request: Optional[Union[registry_service.CreateApiRequest, dict]] = None, - *, - parent: Optional[str] = None, - api: Optional[registry_models.Api] = None, - api_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Api: - r"""Creates a specified API. - - .. 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 apigee_registry_v1 - - def sample_create_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiRequest( - parent="parent_value", - api_id="api_id_value", - ) - - # Make the request - response = client.create_api(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.CreateApiRequest, dict]): - The request object. Request message for CreateApi. - parent (str): - Required. The parent, which owns this collection of - APIs. Format: ``projects/*/locations/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api (google.cloud.apigee_registry_v1.types.Api): - Required. The API to create. - This corresponds to the ``api`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_id (str): - Required. The ID to use for the API, which will become - the final component of the API's resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - # 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, api, api_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.CreateApiRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.CreateApiRequest): - request = registry_service.CreateApiRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api is not None: - request.api = api - if api_id is not None: - request.api_id = api_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_api] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_api(self, - request: Optional[Union[registry_service.UpdateApiRequest, dict]] = None, - *, - api: Optional[registry_models.Api] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Api: - r"""Used to modify a specified API. - - .. 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 apigee_registry_v1 - - def sample_update_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiRequest( - ) - - # Make the request - response = client.update_api(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.UpdateApiRequest, dict]): - The request object. Request message for UpdateApi. - api (google.cloud.apigee_registry_v1.types.Api): - Required. The API to update. - - The ``name`` field is used to identify the API to - update. Format: ``projects/*/locations/*/apis/*`` - - This corresponds to the ``api`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - # 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([api, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.UpdateApiRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.UpdateApiRequest): - request = registry_service.UpdateApiRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api is not None: - request.api = api - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_api] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api.name", request.api.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_api(self, - request: Optional[Union[registry_service.DeleteApiRequest, 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]] = (), - ) -> None: - r"""Removes a specified API and all of the resources that - it owns. - - .. 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 apigee_registry_v1 - - def sample_delete_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiRequest( - name="name_value", - ) - - # Make the request - client.delete_api(request=request) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteApiRequest, dict]): - The request object. Request message for DeleteApi. - name (str): - Required. The name of the API to delete. Format: - ``projects/*/locations/*/apis/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 registry_service.DeleteApiRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.DeleteApiRequest): - request = registry_service.DeleteApiRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_api] - - # 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 list_api_versions(self, - request: Optional[Union[registry_service.ListApiVersionsRequest, 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.ListApiVersionsPager: - r"""Returns matching versions. - - .. 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 apigee_registry_v1 - - def sample_list_api_versions(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ListApiVersionsRequest, dict]): - The request object. Request message for ListApiVersions. - parent (str): - Required. The parent, which owns this collection of - versions. Format: ``projects/*/locations/*/apis/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApiVersionsPager: - Response message for ListApiVersions. - 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 registry_service.ListApiVersionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ListApiVersionsRequest): - request = registry_service.ListApiVersionsRequest(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_api_versions] - - # 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.ListApiVersionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_api_version(self, - request: Optional[Union[registry_service.GetApiVersionRequest, 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]] = (), - ) -> registry_models.ApiVersion: - r"""Returns a specified version. - - .. 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 apigee_registry_v1 - - def sample_get_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetApiVersionRequest, dict]): - The request object. Request message for GetApiVersion. - name (str): - Required. The name of the version to retrieve. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - 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.apigee_registry_v1.types.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - # 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 registry_service.GetApiVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.GetApiVersionRequest): - request = registry_service.GetApiVersionRequest(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_api_version] - - # 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 create_api_version(self, - request: Optional[Union[registry_service.CreateApiVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - api_version: Optional[registry_models.ApiVersion] = None, - api_version_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiVersion: - r"""Creates a specified version. - - .. 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 apigee_registry_v1 - - def sample_create_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiVersionRequest( - parent="parent_value", - api_version_id="api_version_id_value", - ) - - # Make the request - response = client.create_api_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.CreateApiVersionRequest, dict]): - The request object. Request message for - CreateApiVersion. - parent (str): - Required. The parent, which owns this collection of - versions. Format: ``projects/*/locations/*/apis/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_version (google.cloud.apigee_registry_v1.types.ApiVersion): - Required. The version to create. - This corresponds to the ``api_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_version_id (str): - Required. The ID to use for the version, which will - become the final component of the version's resource - name. - - This value should be 1-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_version_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - # 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, api_version, api_version_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.CreateApiVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.CreateApiVersionRequest): - request = registry_service.CreateApiVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api_version is not None: - request.api_version = api_version - if api_version_id is not None: - request.api_version_id = api_version_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_api_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_api_version(self, - request: Optional[Union[registry_service.UpdateApiVersionRequest, dict]] = None, - *, - api_version: Optional[registry_models.ApiVersion] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiVersion: - r"""Used to modify a specified version. - - .. 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 apigee_registry_v1 - - def sample_update_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiVersionRequest( - ) - - # Make the request - response = client.update_api_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest, dict]): - The request object. Request message for - UpdateApiVersion. - api_version (google.cloud.apigee_registry_v1.types.ApiVersion): - Required. The version to update. - - The ``name`` field is used to identify the version to - update. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - This corresponds to the ``api_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - # 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([api_version, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.UpdateApiVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.UpdateApiVersionRequest): - request = registry_service.UpdateApiVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api_version is not None: - request.api_version = api_version - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_api_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api_version.name", request.api_version.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_api_version(self, - request: Optional[Union[registry_service.DeleteApiVersionRequest, 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]] = (), - ) -> None: - r"""Removes a specified version and all of the resources - that it owns. - - .. 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 apigee_registry_v1 - - def sample_delete_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiVersionRequest( - name="name_value", - ) - - # Make the request - client.delete_api_version(request=request) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest, dict]): - The request object. Request message for - DeleteApiVersion. - name (str): - Required. The name of the version to delete. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 registry_service.DeleteApiVersionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.DeleteApiVersionRequest): - request = registry_service.DeleteApiVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_api_version] - - # 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 list_api_specs(self, - request: Optional[Union[registry_service.ListApiSpecsRequest, 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.ListApiSpecsPager: - r"""Returns matching specs. - - .. 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 apigee_registry_v1 - - def sample_list_api_specs(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_specs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ListApiSpecsRequest, dict]): - The request object. Request message for ListApiSpecs. - parent (str): - Required. The parent, which owns this collection of - specs. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApiSpecsPager: - Response message for ListApiSpecs. - 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 registry_service.ListApiSpecsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ListApiSpecsRequest): - request = registry_service.ListApiSpecsRequest(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_api_specs] - - # 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.ListApiSpecsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_api_spec(self, - request: Optional[Union[registry_service.GetApiSpecRequest, 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]] = (), - ) -> registry_models.ApiSpec: - r"""Returns a specified spec. - - .. 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 apigee_registry_v1 - - def sample_get_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetApiSpecRequest, dict]): - The request object. Request message for GetApiSpec. - name (str): - Required. The name of the spec to retrieve. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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 registry_service.GetApiSpecRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.GetApiSpecRequest): - request = registry_service.GetApiSpecRequest(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_api_spec] - - # 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_api_spec_contents(self, - request: Optional[Union[registry_service.GetApiSpecContentsRequest, 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]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Returns the contents of a specified spec. If specs are stored - with GZip compression, the default behavior is to return the - spec uncompressed (the mime_type response field indicates the - exact format returned). - - .. 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 apigee_registry_v1 - - def sample_get_api_spec_contents(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecContentsRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_spec_contents(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest, dict]): - The request object. Request message for - GetApiSpecContents. - name (str): - Required. The name of the spec whose contents should be - retrieved. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # 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 registry_service.GetApiSpecContentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.GetApiSpecContentsRequest): - request = registry_service.GetApiSpecContentsRequest(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_api_spec_contents] - - # 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 create_api_spec(self, - request: Optional[Union[registry_service.CreateApiSpecRequest, dict]] = None, - *, - parent: Optional[str] = None, - api_spec: Optional[registry_models.ApiSpec] = None, - api_spec_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Creates a specified spec. - - .. 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 apigee_registry_v1 - - def sample_create_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiSpecRequest( - parent="parent_value", - api_spec_id="api_spec_id_value", - ) - - # Make the request - response = client.create_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.CreateApiSpecRequest, dict]): - The request object. Request message for CreateApiSpec. - parent (str): - Required. The parent, which owns this collection of - specs. Format: - ``projects/*/locations/*/apis/*/versions/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): - Required. The spec to create. - This corresponds to the ``api_spec`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_spec_id (str): - Required. The ID to use for the spec, which will become - the final component of the spec's resource name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_spec_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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, api_spec, api_spec_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.CreateApiSpecRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.CreateApiSpecRequest): - request = registry_service.CreateApiSpecRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api_spec is not None: - request.api_spec = api_spec - if api_spec_id is not None: - request.api_spec_id = api_spec_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_api_spec] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_api_spec(self, - request: Optional[Union[registry_service.UpdateApiSpecRequest, dict]] = None, - *, - api_spec: Optional[registry_models.ApiSpec] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Used to modify a specified spec. - - .. 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 apigee_registry_v1 - - def sample_update_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiSpecRequest( - ) - - # Make the request - response = client.update_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest, dict]): - The request object. Request message for UpdateApiSpec. - api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): - Required. The spec to update. - - The ``name`` field is used to identify the spec to - update. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - This corresponds to the ``api_spec`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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([api_spec, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.UpdateApiSpecRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.UpdateApiSpecRequest): - request = registry_service.UpdateApiSpecRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api_spec is not None: - request.api_spec = api_spec - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_api_spec] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api_spec.name", request.api_spec.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_api_spec(self, - request: Optional[Union[registry_service.DeleteApiSpecRequest, 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]] = (), - ) -> None: - r"""Removes a specified spec, all revisions, and all - child resources (e.g., artifacts). - - .. 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 apigee_registry_v1 - - def sample_delete_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRequest( - name="name_value", - ) - - # Make the request - client.delete_api_spec(request=request) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest, dict]): - The request object. Request message for DeleteApiSpec. - name (str): - Required. The name of the spec to delete. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 registry_service.DeleteApiSpecRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.DeleteApiSpecRequest): - request = registry_service.DeleteApiSpecRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_api_spec] - - # 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 tag_api_spec_revision(self, - request: Optional[Union[registry_service.TagApiSpecRevisionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Adds a tag to a specified revision of a spec. - - .. 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 apigee_registry_v1 - - def sample_tag_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiSpecRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = client.tag_api_spec_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest, dict]): - The request object. Request message for - TagApiSpecRevision. - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.TagApiSpecRevisionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.TagApiSpecRevisionRequest): - request = registry_service.TagApiSpecRevisionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.tag_api_spec_revision] - - # 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_api_spec_revisions(self, - request: Optional[Union[registry_service.ListApiSpecRevisionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListApiSpecRevisionsPager: - r"""Lists all revisions of a spec. - Revisions are returned in descending order of revision - creation time. - - .. 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 apigee_registry_v1 - - def sample_list_api_spec_revisions(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_spec_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest, dict]): - The request object. Request message for - ListApiSpecRevisions. - 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.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsPager: - Response message for - ListApiSpecRevisionsResponse. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.ListApiSpecRevisionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ListApiSpecRevisionsRequest): - request = registry_service.ListApiSpecRevisionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_api_spec_revisions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListApiSpecRevisionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def rollback_api_spec(self, - request: Optional[Union[registry_service.RollbackApiSpecRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiSpec: - r"""Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - .. 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 apigee_registry_v1 - - def sample_rollback_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiSpecRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = client.rollback_api_spec(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest, dict]): - The request object. Request message for RollbackApiSpec. - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.RollbackApiSpecRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.RollbackApiSpecRequest): - request = registry_service.RollbackApiSpecRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rollback_api_spec] - - # 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_api_spec_revision(self, - request: Optional[Union[registry_service.DeleteApiSpecRevisionRequest, 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]] = (), - ) -> registry_models.ApiSpec: - r"""Deletes a revision of a spec. - - .. 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 apigee_registry_v1 - - def sample_delete_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.delete_api_spec_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest, dict]): - The request object. Request message for - DeleteApiSpecRevision. - name (str): - Required. The name of the spec revision to be deleted, - with a revision ID explicitly included. - - Example: - ``projects/sample/locations/global/apis/petstore/versions/1.0.0/specs/openapi.yaml@c7cfa2a8`` - - 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.apigee_registry_v1.types.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - # 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 registry_service.DeleteApiSpecRevisionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.DeleteApiSpecRevisionRequest): - request = registry_service.DeleteApiSpecRevisionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_api_spec_revision] - - # 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_api_deployments(self, - request: Optional[Union[registry_service.ListApiDeploymentsRequest, 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.ListApiDeploymentsPager: - r"""Returns matching deployments. - - .. 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 apigee_registry_v1 - - def sample_list_api_deployments(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_deployments(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest, dict]): - The request object. Request message for - ListApiDeployments. - parent (str): - Required. The parent, which owns this collection of - deployments. Format: ``projects/*/locations/*/apis/*`` - - 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsPager: - Response message for - ListApiDeployments. - 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 registry_service.ListApiDeploymentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ListApiDeploymentsRequest): - request = registry_service.ListApiDeploymentsRequest(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_api_deployments] - - # 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.ListApiDeploymentsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_api_deployment(self, - request: Optional[Union[registry_service.GetApiDeploymentRequest, 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]] = (), - ) -> registry_models.ApiDeployment: - r"""Returns a specified deployment. - - .. 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 apigee_registry_v1 - - def sample_get_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiDeploymentRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest, dict]): - The request object. Request message for - GetApiDeployment. - name (str): - Required. The name of the deployment to retrieve. - Format: ``projects/*/locations/*/apis/*/deployments/*`` - - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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 registry_service.GetApiDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.GetApiDeploymentRequest): - request = registry_service.GetApiDeploymentRequest(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_api_deployment] - - # 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 create_api_deployment(self, - request: Optional[Union[registry_service.CreateApiDeploymentRequest, dict]] = None, - *, - parent: Optional[str] = None, - api_deployment: Optional[registry_models.ApiDeployment] = None, - api_deployment_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Creates a specified deployment. - - .. 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 apigee_registry_v1 - - def sample_create_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiDeploymentRequest( - parent="parent_value", - api_deployment_id="api_deployment_id_value", - ) - - # Make the request - response = client.create_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest, dict]): - The request object. Request message for - CreateApiDeployment. - parent (str): - Required. The parent, which owns this collection of - deployments. Format: ``projects/*/locations/*/apis/*`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): - Required. The deployment to create. - This corresponds to the ``api_deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - api_deployment_id (str): - Required. The ID to use for the deployment, which will - become the final component of the deployment's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``api_deployment_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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, api_deployment, api_deployment_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.CreateApiDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.CreateApiDeploymentRequest): - request = registry_service.CreateApiDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if api_deployment is not None: - request.api_deployment = api_deployment - if api_deployment_id is not None: - request.api_deployment_id = api_deployment_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_api_deployment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_api_deployment(self, - request: Optional[Union[registry_service.UpdateApiDeploymentRequest, dict]] = None, - *, - api_deployment: Optional[registry_models.ApiDeployment] = None, - update_mask: Optional[field_mask_pb2.FieldMask] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Used to modify a specified deployment. - - .. 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 apigee_registry_v1 - - def sample_update_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiDeploymentRequest( - ) - - # Make the request - response = client.update_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest, dict]): - The request object. Request message for - UpdateApiDeployment. - api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): - Required. The deployment to update. - - The ``name`` field is used to identify the deployment to - update. Format: - ``projects/*/locations/*/apis/*/deployments/*`` - - This corresponds to the ``api_deployment`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields - are updated that are set in the request message (fields - set to default values are ignored). If an asterisk "*" - is specified, all fields are updated, including fields - that are unspecified/default in the request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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([api_deployment, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.UpdateApiDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.UpdateApiDeploymentRequest): - request = registry_service.UpdateApiDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if api_deployment is not None: - request.api_deployment = api_deployment - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_api_deployment] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("api_deployment.name", request.api_deployment.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_api_deployment(self, - request: Optional[Union[registry_service.DeleteApiDeploymentRequest, 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]] = (), - ) -> None: - r"""Removes a specified deployment, all revisions, and - all child resources (e.g., artifacts). - - .. 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 apigee_registry_v1 - - def sample_delete_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRequest( - name="name_value", - ) - - # Make the request - client.delete_api_deployment(request=request) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest, dict]): - The request object. Request message for - DeleteApiDeployment. - name (str): - Required. The name of the deployment to delete. Format: - ``projects/*/locations/*/apis/*/deployments/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 registry_service.DeleteApiDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.DeleteApiDeploymentRequest): - request = registry_service.DeleteApiDeploymentRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_api_deployment] - - # 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 tag_api_deployment_revision(self, - request: Optional[Union[registry_service.TagApiDeploymentRevisionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Adds a tag to a specified revision of a - deployment. - - .. 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 apigee_registry_v1 - - def sample_tag_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiDeploymentRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = client.tag_api_deployment_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest, dict]): - The request object. Request message for - TagApiDeploymentRevision. - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.TagApiDeploymentRevisionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.TagApiDeploymentRevisionRequest): - request = registry_service.TagApiDeploymentRevisionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.tag_api_deployment_revision] - - # 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_api_deployment_revisions(self, - request: Optional[Union[registry_service.ListApiDeploymentRevisionsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListApiDeploymentRevisionsPager: - r"""Lists all revisions of a deployment. - Revisions are returned in descending order of revision - creation time. - - .. 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 apigee_registry_v1 - - def sample_list_api_deployment_revisions(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_deployment_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest, dict]): - The request object. Request message for - ListApiDeploymentRevisions. - 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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsPager: - Response message for - ListApiDeploymentRevisionsResponse. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.ListApiDeploymentRevisionsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ListApiDeploymentRevisionsRequest): - request = registry_service.ListApiDeploymentRevisionsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_api_deployment_revisions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListApiDeploymentRevisionsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def rollback_api_deployment(self, - request: Optional[Union[registry_service.RollbackApiDeploymentRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.ApiDeployment: - r"""Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - .. 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 apigee_registry_v1 - - def sample_rollback_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiDeploymentRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = client.rollback_api_deployment(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest, dict]): - The request object. Request message for - RollbackApiDeployment. - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.RollbackApiDeploymentRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.RollbackApiDeploymentRequest): - request = registry_service.RollbackApiDeploymentRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.rollback_api_deployment] - - # 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_api_deployment_revision(self, - request: Optional[Union[registry_service.DeleteApiDeploymentRevisionRequest, 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]] = (), - ) -> registry_models.ApiDeployment: - r"""Deletes a revision of a deployment. - - .. 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 apigee_registry_v1 - - def sample_delete_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.delete_api_deployment_revision(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest, dict]): - The request object. Request message for - DeleteApiDeploymentRevision. - name (str): - Required. The name of the deployment revision to be - deleted, with a revision ID explicitly included. - - Example: - ``projects/sample/locations/global/apis/petstore/deployments/prod@c7cfa2a8`` - - 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.apigee_registry_v1.types.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - # 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 registry_service.DeleteApiDeploymentRevisionRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.DeleteApiDeploymentRevisionRequest): - request = registry_service.DeleteApiDeploymentRevisionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_api_deployment_revision] - - # 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_artifacts(self, - request: Optional[Union[registry_service.ListArtifactsRequest, 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.ListArtifactsPager: - r"""Returns matching artifacts. - - .. 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 apigee_registry_v1 - - def sample_list_artifacts(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListArtifactsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_artifacts(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ListArtifactsRequest, dict]): - The request object. Request message for ListArtifacts. - parent (str): - Required. The parent, which owns this collection of - artifacts. Format: ``{parent}`` - - 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.apigee_registry_v1.services.registry.pagers.ListArtifactsPager: - Response message for ListArtifacts. - 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 registry_service.ListArtifactsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ListArtifactsRequest): - request = registry_service.ListArtifactsRequest(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_artifacts] - - # 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.ListArtifactsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_artifact(self, - request: Optional[Union[registry_service.GetArtifactRequest, 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]] = (), - ) -> registry_models.Artifact: - r"""Returns a specified artifact. - - .. 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 apigee_registry_v1 - - def sample_get_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactRequest( - name="name_value", - ) - - # Make the request - response = client.get_artifact(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetArtifactRequest, dict]): - The request object. Request message for GetArtifact. - name (str): - Required. The name of the artifact to retrieve. Format: - ``{parent}/artifacts/*`` - - 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.apigee_registry_v1.types.Artifact: - Artifacts of resources. Artifacts are unique (single-value) per resource - and are used to store metadata that is too large or - numerous to be stored directly on the resource. Since - artifacts are stored separately from parent - resources, they should generally be used for metadata - that is needed infrequently, i.e., not for display in - primary views of the resource but perhaps displayed - or downloaded upon request. The ListArtifacts method - allows artifacts to be quickly enumerated and checked - for presence without downloading their - (potentially-large) contents. - - """ - # 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 registry_service.GetArtifactRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.GetArtifactRequest): - request = registry_service.GetArtifactRequest(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_artifact] - - # 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_artifact_contents(self, - request: Optional[Union[registry_service.GetArtifactContentsRequest, 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]] = (), - ) -> httpbody_pb2.HttpBody: - r"""Returns the contents of a specified artifact. If artifacts are - stored with GZip compression, the default behavior is to return - the artifact uncompressed (the mime_type response field - indicates the exact format returned). - - .. 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 apigee_registry_v1 - - def sample_get_artifact_contents(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactContentsRequest( - name="name_value", - ) - - # Make the request - response = client.get_artifact_contents(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest, dict]): - The request object. Request message for - GetArtifactContents. - name (str): - Required. The name of the artifact whose contents should - be retrieved. Format: ``{parent}/artifacts/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It should only be used for - payload formats that can't be represented as JSON, - such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as - the response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request - fields and also want access to the raw HTTP body. - - Example: - - message GetResourceRequest { - // A unique request id. string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - # 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 registry_service.GetArtifactContentsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.GetArtifactContentsRequest): - request = registry_service.GetArtifactContentsRequest(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_artifact_contents] - - # 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 create_artifact(self, - request: Optional[Union[registry_service.CreateArtifactRequest, dict]] = None, - *, - parent: Optional[str] = None, - artifact: Optional[registry_models.Artifact] = None, - artifact_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Artifact: - r"""Creates a specified artifact. - - .. 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 apigee_registry_v1 - - def sample_create_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateArtifactRequest( - parent="parent_value", - artifact_id="artifact_id_value", - ) - - # Make the request - response = client.create_artifact(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.CreateArtifactRequest, dict]): - The request object. Request message for CreateArtifact. - parent (str): - Required. The parent, which owns this collection of - artifacts. Format: ``{parent}`` - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - artifact (google.cloud.apigee_registry_v1.types.Artifact): - Required. The artifact to create. - This corresponds to the ``artifact`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - artifact_id (str): - Required. The ID to use for the artifact, which will - become the final component of the artifact's resource - name. - - This value should be 4-63 characters, and valid - characters are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - - This corresponds to the ``artifact_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.apigee_registry_v1.types.Artifact: - Artifacts of resources. Artifacts are unique (single-value) per resource - and are used to store metadata that is too large or - numerous to be stored directly on the resource. Since - artifacts are stored separately from parent - resources, they should generally be used for metadata - that is needed infrequently, i.e., not for display in - primary views of the resource but perhaps displayed - or downloaded upon request. The ListArtifacts method - allows artifacts to be quickly enumerated and checked - for presence without downloading their - (potentially-large) contents. - - """ - # 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, artifact, artifact_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # Minor optimization to avoid making a copy if the user passes - # in a registry_service.CreateArtifactRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.CreateArtifactRequest): - request = registry_service.CreateArtifactRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if artifact is not None: - request.artifact = artifact - if artifact_id is not None: - request.artifact_id = artifact_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_artifact] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def replace_artifact(self, - request: Optional[Union[registry_service.ReplaceArtifactRequest, dict]] = None, - *, - artifact: Optional[registry_models.Artifact] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> registry_models.Artifact: - r"""Used to replace a specified artifact. - - .. 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 apigee_registry_v1 - - def sample_replace_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ReplaceArtifactRequest( - ) - - # Make the request - response = client.replace_artifact(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest, dict]): - The request object. Request message for ReplaceArtifact. - artifact (google.cloud.apigee_registry_v1.types.Artifact): - Required. The artifact to replace. - - The ``name`` field is used to identify the artifact to - replace. Format: ``{parent}/artifacts/*`` - - This corresponds to the ``artifact`` 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.apigee_registry_v1.types.Artifact: - Artifacts of resources. Artifacts are unique (single-value) per resource - and are used to store metadata that is too large or - numerous to be stored directly on the resource. Since - artifacts are stored separately from parent - resources, they should generally be used for metadata - that is needed infrequently, i.e., not for display in - primary views of the resource but perhaps displayed - or downloaded upon request. The ListArtifacts method - allows artifacts to be quickly enumerated and checked - for presence without downloading their - (potentially-large) contents. - - """ - # 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([artifact]) - 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 registry_service.ReplaceArtifactRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.ReplaceArtifactRequest): - request = registry_service.ReplaceArtifactRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if artifact is not None: - request.artifact = artifact - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.replace_artifact] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("artifact.name", request.artifact.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_artifact(self, - request: Optional[Union[registry_service.DeleteArtifactRequest, 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]] = (), - ) -> None: - r"""Removes a specified artifact. - - .. 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 apigee_registry_v1 - - def sample_delete_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteArtifactRequest( - name="name_value", - ) - - # Make the request - client.delete_artifact(request=request) - - Args: - request (Union[google.cloud.apigee_registry_v1.types.DeleteArtifactRequest, dict]): - The request object. Request message for DeleteArtifact. - name (str): - Required. The name of the artifact to delete. Format: - ``{parent}/artifacts/*`` - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # 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 registry_service.DeleteArtifactRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, registry_service.DeleteArtifactRequest): - request = registry_service.DeleteArtifactRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_artifact] - - # 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 __enter__(self) -> "RegistryClient": - return self - - def __exit__(self, type, value, traceback): - """Releases underlying transport's resources. - - .. warning:: - ONLY use as a context manager if the transport is NOT shared - with other clients! Exiting the with block will CLOSE the transport - and may cause errors in other clients! - """ - 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 set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - 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__) - - -__all__ = ( - "RegistryClient", -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py deleted file mode 100644 index fb70da3..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/pagers.py +++ /dev/null @@ -1,866 +0,0 @@ -# -*- 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. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service - - -class ListApisPager: - """A pager for iterating through ``list_apis`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` object, and - provides an ``__iter__`` method to iterate through its - ``apis`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListApis`` requests and continue to iterate - through the ``apis`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` - 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[..., registry_service.ListApisResponse], - request: registry_service.ListApisRequest, - response: registry_service.ListApisResponse, - *, - 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.apigee_registry_v1.types.ListApisRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApisResponse): - 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 = registry_service.ListApisRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registry_service.ListApisResponse]: - 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[registry_models.Api]: - for page in self.pages: - yield from page.apis - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApisAsyncPager: - """A pager for iterating through ``list_apis`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``apis`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListApis`` requests and continue to iterate - through the ``apis`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApisResponse` - 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[registry_service.ListApisResponse]], - request: registry_service.ListApisRequest, - response: registry_service.ListApisResponse, - *, - 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.apigee_registry_v1.types.ListApisRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApisResponse): - 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 = registry_service.ListApisRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registry_service.ListApisResponse]: - 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[registry_models.Api]: - async def async_generator(): - async for page in self.pages: - for response in page.apis: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiVersionsPager: - """A pager for iterating through ``list_api_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``api_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListApiVersions`` requests and continue to iterate - through the ``api_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` - 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[..., registry_service.ListApiVersionsResponse], - request: registry_service.ListApiVersionsRequest, - response: registry_service.ListApiVersionsResponse, - *, - 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.apigee_registry_v1.types.ListApiVersionsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiVersionsResponse): - 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 = registry_service.ListApiVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registry_service.ListApiVersionsResponse]: - 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[registry_models.ApiVersion]: - for page in self.pages: - yield from page.api_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiVersionsAsyncPager: - """A pager for iterating through ``list_api_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``api_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListApiVersions`` requests and continue to iterate - through the ``api_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiVersionsResponse` - 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[registry_service.ListApiVersionsResponse]], - request: registry_service.ListApiVersionsRequest, - response: registry_service.ListApiVersionsResponse, - *, - 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.apigee_registry_v1.types.ListApiVersionsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiVersionsResponse): - 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 = registry_service.ListApiVersionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registry_service.ListApiVersionsResponse]: - 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[registry_models.ApiVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.api_versions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiSpecsPager: - """A pager for iterating through ``list_api_specs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``api_specs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListApiSpecs`` requests and continue to iterate - through the ``api_specs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` - 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[..., registry_service.ListApiSpecsResponse], - request: registry_service.ListApiSpecsRequest, - response: registry_service.ListApiSpecsResponse, - *, - 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.apigee_registry_v1.types.ListApiSpecsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiSpecsResponse): - 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 = registry_service.ListApiSpecsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registry_service.ListApiSpecsResponse]: - 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[registry_models.ApiSpec]: - for page in self.pages: - yield from page.api_specs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiSpecsAsyncPager: - """A pager for iterating through ``list_api_specs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``api_specs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListApiSpecs`` requests and continue to iterate - through the ``api_specs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecsResponse` - 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[registry_service.ListApiSpecsResponse]], - request: registry_service.ListApiSpecsRequest, - response: registry_service.ListApiSpecsResponse, - *, - 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.apigee_registry_v1.types.ListApiSpecsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiSpecsResponse): - 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 = registry_service.ListApiSpecsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registry_service.ListApiSpecsResponse]: - 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[registry_models.ApiSpec]: - async def async_generator(): - async for page in self.pages: - for response in page.api_specs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiSpecRevisionsPager: - """A pager for iterating through ``list_api_spec_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``api_specs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListApiSpecRevisions`` requests and continue to iterate - through the ``api_specs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` - 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[..., registry_service.ListApiSpecRevisionsResponse], - request: registry_service.ListApiSpecRevisionsRequest, - response: registry_service.ListApiSpecRevisionsResponse, - *, - 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.apigee_registry_v1.types.ListApiSpecRevisionsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse): - 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 = registry_service.ListApiSpecRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registry_service.ListApiSpecRevisionsResponse]: - 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[registry_models.ApiSpec]: - for page in self.pages: - yield from page.api_specs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiSpecRevisionsAsyncPager: - """A pager for iterating through ``list_api_spec_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``api_specs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListApiSpecRevisions`` requests and continue to iterate - through the ``api_specs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse` - 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[registry_service.ListApiSpecRevisionsResponse]], - request: registry_service.ListApiSpecRevisionsRequest, - response: registry_service.ListApiSpecRevisionsResponse, - *, - 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.apigee_registry_v1.types.ListApiSpecRevisionsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsResponse): - 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 = registry_service.ListApiSpecRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registry_service.ListApiSpecRevisionsResponse]: - 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[registry_models.ApiSpec]: - async def async_generator(): - async for page in self.pages: - for response in page.api_specs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiDeploymentsPager: - """A pager for iterating through ``list_api_deployments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``api_deployments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListApiDeployments`` requests and continue to iterate - through the ``api_deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` - 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[..., registry_service.ListApiDeploymentsResponse], - request: registry_service.ListApiDeploymentsRequest, - response: registry_service.ListApiDeploymentsResponse, - *, - 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.apigee_registry_v1.types.ListApiDeploymentsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse): - 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 = registry_service.ListApiDeploymentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registry_service.ListApiDeploymentsResponse]: - 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[registry_models.ApiDeployment]: - for page in self.pages: - yield from page.api_deployments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiDeploymentsAsyncPager: - """A pager for iterating through ``list_api_deployments`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``api_deployments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListApiDeployments`` requests and continue to iterate - through the ``api_deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse` - 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[registry_service.ListApiDeploymentsResponse]], - request: registry_service.ListApiDeploymentsRequest, - response: registry_service.ListApiDeploymentsResponse, - *, - 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.apigee_registry_v1.types.ListApiDeploymentsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiDeploymentsResponse): - 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 = registry_service.ListApiDeploymentsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registry_service.ListApiDeploymentsResponse]: - 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[registry_models.ApiDeployment]: - async def async_generator(): - async for page in self.pages: - for response in page.api_deployments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiDeploymentRevisionsPager: - """A pager for iterating through ``list_api_deployment_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``api_deployments`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListApiDeploymentRevisions`` requests and continue to iterate - through the ``api_deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` - 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[..., registry_service.ListApiDeploymentRevisionsResponse], - request: registry_service.ListApiDeploymentRevisionsRequest, - response: registry_service.ListApiDeploymentRevisionsResponse, - *, - 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.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse): - 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 = registry_service.ListApiDeploymentRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registry_service.ListApiDeploymentRevisionsResponse]: - 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[registry_models.ApiDeployment]: - for page in self.pages: - yield from page.api_deployments - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListApiDeploymentRevisionsAsyncPager: - """A pager for iterating through ``list_api_deployment_revisions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``api_deployments`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListApiDeploymentRevisions`` requests and continue to iterate - through the ``api_deployments`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse` - 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[registry_service.ListApiDeploymentRevisionsResponse]], - request: registry_service.ListApiDeploymentRevisionsRequest, - response: registry_service.ListApiDeploymentRevisionsResponse, - *, - 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.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsResponse): - 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 = registry_service.ListApiDeploymentRevisionsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registry_service.ListApiDeploymentRevisionsResponse]: - 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[registry_models.ApiDeployment]: - async def async_generator(): - async for page in self.pages: - for response in page.api_deployments: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListArtifactsPager: - """A pager for iterating through ``list_artifacts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``artifacts`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListArtifacts`` requests and continue to iterate - through the ``artifacts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` - 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[..., registry_service.ListArtifactsResponse], - request: registry_service.ListArtifactsRequest, - response: registry_service.ListArtifactsResponse, - *, - 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.apigee_registry_v1.types.ListArtifactsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListArtifactsResponse): - 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 = registry_service.ListArtifactsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[registry_service.ListArtifactsResponse]: - 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[registry_models.Artifact]: - for page in self.pages: - yield from page.artifacts - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListArtifactsAsyncPager: - """A pager for iterating through ``list_artifacts`` requests. - - This class thinly wraps an initial - :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``artifacts`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListArtifacts`` requests and continue to iterate - through the ``artifacts`` field on the - corresponding responses. - - All the usual :class:`google.cloud.apigee_registry_v1.types.ListArtifactsResponse` - 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[registry_service.ListArtifactsResponse]], - request: registry_service.ListArtifactsRequest, - response: registry_service.ListArtifactsResponse, - *, - 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.apigee_registry_v1.types.ListArtifactsRequest): - The initial request object. - response (google.cloud.apigee_registry_v1.types.ListArtifactsResponse): - 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 = registry_service.ListArtifactsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[registry_service.ListArtifactsResponse]: - 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[registry_models.Artifact]: - async def async_generator(): - async for page in self.pages: - for response in page.artifacts: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py deleted file mode 100644 index 8e7b424..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- 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. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import RegistryTransport -from .grpc import RegistryGrpcTransport -from .grpc_asyncio import RegistryGrpcAsyncIOTransport -from .rest import RegistryRestTransport -from .rest import RegistryRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[RegistryTransport]] -_transport_registry['grpc'] = RegistryGrpcTransport -_transport_registry['grpc_asyncio'] = RegistryGrpcAsyncIOTransport -_transport_registry['rest'] = RegistryRestTransport - -__all__ = ( - 'RegistryTransport', - 'RegistryGrpcTransport', - 'RegistryGrpcAsyncIOTransport', - 'RegistryRestTransport', - 'RegistryRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py deleted file mode 100644 index 90a2f72..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/base.py +++ /dev/null @@ -1,1010 +0,0 @@ -# -*- 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. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.apigee_registry_v1 import gapic_version as package_version - -import google.auth # type: ignore -import google.api_core -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service -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 empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class RegistryTransport(abc.ABC): - """Abstract transport class for Registry.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'apigeeregistry.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_apis: gapic_v1.method.wrap_method( - self.list_apis, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_api: gapic_v1.method.wrap_method( - self.get_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_api: gapic_v1.method.wrap_method( - self.create_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_api: gapic_v1.method.wrap_method( - self.update_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_api: gapic_v1.method.wrap_method( - self.delete_api, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_api_versions: gapic_v1.method.wrap_method( - self.list_api_versions, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_api_version: gapic_v1.method.wrap_method( - self.get_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_api_version: gapic_v1.method.wrap_method( - self.create_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_api_version: gapic_v1.method.wrap_method( - self.update_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_api_version: gapic_v1.method.wrap_method( - self.delete_api_version, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_api_specs: gapic_v1.method.wrap_method( - self.list_api_specs, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_api_spec: gapic_v1.method.wrap_method( - self.get_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_api_spec_contents: gapic_v1.method.wrap_method( - self.get_api_spec_contents, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_api_spec: gapic_v1.method.wrap_method( - self.create_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_api_spec: gapic_v1.method.wrap_method( - self.update_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_api_spec: gapic_v1.method.wrap_method( - self.delete_api_spec, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.tag_api_spec_revision: gapic_v1.method.wrap_method( - self.tag_api_spec_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_api_spec_revisions: gapic_v1.method.wrap_method( - self.list_api_spec_revisions, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.rollback_api_spec: gapic_v1.method.wrap_method( - self.rollback_api_spec, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_api_spec_revision: gapic_v1.method.wrap_method( - self.delete_api_spec_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_api_deployments: gapic_v1.method.wrap_method( - self.list_api_deployments, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_api_deployment: gapic_v1.method.wrap_method( - self.get_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_api_deployment: gapic_v1.method.wrap_method( - self.create_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_api_deployment: gapic_v1.method.wrap_method( - self.update_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_api_deployment: gapic_v1.method.wrap_method( - self.delete_api_deployment, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.tag_api_deployment_revision: gapic_v1.method.wrap_method( - self.tag_api_deployment_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_api_deployment_revisions: gapic_v1.method.wrap_method( - self.list_api_deployment_revisions, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.rollback_api_deployment: gapic_v1.method.wrap_method( - self.rollback_api_deployment, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_api_deployment_revision: gapic_v1.method.wrap_method( - self.delete_api_deployment_revision, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_artifacts: gapic_v1.method.wrap_method( - self.list_artifacts, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_artifact: gapic_v1.method.wrap_method( - self.get_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_artifact_contents: gapic_v1.method.wrap_method( - self.get_artifact_contents, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_artifact: gapic_v1.method.wrap_method( - self.create_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.replace_artifact: gapic_v1.method.wrap_method( - self.replace_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.delete_artifact: gapic_v1.method.wrap_method( - self.delete_artifact, - default_retry=retries.Retry( -initial=0.2,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.Aborted, - core_exceptions.Cancelled, - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - def close(self): - """Closes resources associated with the transport. - - .. warning:: - Only call this method if the transport is NOT shared - with other clients - this may cause errors in other clients! - """ - raise NotImplementedError() - - @property - def list_apis(self) -> Callable[ - [registry_service.ListApisRequest], - Union[ - registry_service.ListApisResponse, - Awaitable[registry_service.ListApisResponse] - ]]: - raise NotImplementedError() - - @property - def get_api(self) -> Callable[ - [registry_service.GetApiRequest], - Union[ - registry_models.Api, - Awaitable[registry_models.Api] - ]]: - raise NotImplementedError() - - @property - def create_api(self) -> Callable[ - [registry_service.CreateApiRequest], - Union[ - registry_models.Api, - Awaitable[registry_models.Api] - ]]: - raise NotImplementedError() - - @property - def update_api(self) -> Callable[ - [registry_service.UpdateApiRequest], - Union[ - registry_models.Api, - Awaitable[registry_models.Api] - ]]: - raise NotImplementedError() - - @property - def delete_api(self) -> Callable[ - [registry_service.DeleteApiRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_api_versions(self) -> Callable[ - [registry_service.ListApiVersionsRequest], - Union[ - registry_service.ListApiVersionsResponse, - Awaitable[registry_service.ListApiVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_api_version(self) -> Callable[ - [registry_service.GetApiVersionRequest], - Union[ - registry_models.ApiVersion, - Awaitable[registry_models.ApiVersion] - ]]: - raise NotImplementedError() - - @property - def create_api_version(self) -> Callable[ - [registry_service.CreateApiVersionRequest], - Union[ - registry_models.ApiVersion, - Awaitable[registry_models.ApiVersion] - ]]: - raise NotImplementedError() - - @property - def update_api_version(self) -> Callable[ - [registry_service.UpdateApiVersionRequest], - Union[ - registry_models.ApiVersion, - Awaitable[registry_models.ApiVersion] - ]]: - raise NotImplementedError() - - @property - def delete_api_version(self) -> Callable[ - [registry_service.DeleteApiVersionRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def list_api_specs(self) -> Callable[ - [registry_service.ListApiSpecsRequest], - Union[ - registry_service.ListApiSpecsResponse, - Awaitable[registry_service.ListApiSpecsResponse] - ]]: - raise NotImplementedError() - - @property - def get_api_spec(self) -> Callable[ - [registry_service.GetApiSpecRequest], - Union[ - registry_models.ApiSpec, - Awaitable[registry_models.ApiSpec] - ]]: - raise NotImplementedError() - - @property - def get_api_spec_contents(self) -> Callable[ - [registry_service.GetApiSpecContentsRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def create_api_spec(self) -> Callable[ - [registry_service.CreateApiSpecRequest], - Union[ - registry_models.ApiSpec, - Awaitable[registry_models.ApiSpec] - ]]: - raise NotImplementedError() - - @property - def update_api_spec(self) -> Callable[ - [registry_service.UpdateApiSpecRequest], - Union[ - registry_models.ApiSpec, - Awaitable[registry_models.ApiSpec] - ]]: - raise NotImplementedError() - - @property - def delete_api_spec(self) -> Callable[ - [registry_service.DeleteApiSpecRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def tag_api_spec_revision(self) -> Callable[ - [registry_service.TagApiSpecRevisionRequest], - Union[ - registry_models.ApiSpec, - Awaitable[registry_models.ApiSpec] - ]]: - raise NotImplementedError() - - @property - def list_api_spec_revisions(self) -> Callable[ - [registry_service.ListApiSpecRevisionsRequest], - Union[ - registry_service.ListApiSpecRevisionsResponse, - Awaitable[registry_service.ListApiSpecRevisionsResponse] - ]]: - raise NotImplementedError() - - @property - def rollback_api_spec(self) -> Callable[ - [registry_service.RollbackApiSpecRequest], - Union[ - registry_models.ApiSpec, - Awaitable[registry_models.ApiSpec] - ]]: - raise NotImplementedError() - - @property - def delete_api_spec_revision(self) -> Callable[ - [registry_service.DeleteApiSpecRevisionRequest], - Union[ - registry_models.ApiSpec, - Awaitable[registry_models.ApiSpec] - ]]: - raise NotImplementedError() - - @property - def list_api_deployments(self) -> Callable[ - [registry_service.ListApiDeploymentsRequest], - Union[ - registry_service.ListApiDeploymentsResponse, - Awaitable[registry_service.ListApiDeploymentsResponse] - ]]: - raise NotImplementedError() - - @property - def get_api_deployment(self) -> Callable[ - [registry_service.GetApiDeploymentRequest], - Union[ - registry_models.ApiDeployment, - Awaitable[registry_models.ApiDeployment] - ]]: - raise NotImplementedError() - - @property - def create_api_deployment(self) -> Callable[ - [registry_service.CreateApiDeploymentRequest], - Union[ - registry_models.ApiDeployment, - Awaitable[registry_models.ApiDeployment] - ]]: - raise NotImplementedError() - - @property - def update_api_deployment(self) -> Callable[ - [registry_service.UpdateApiDeploymentRequest], - Union[ - registry_models.ApiDeployment, - Awaitable[registry_models.ApiDeployment] - ]]: - raise NotImplementedError() - - @property - def delete_api_deployment(self) -> Callable[ - [registry_service.DeleteApiDeploymentRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def tag_api_deployment_revision(self) -> Callable[ - [registry_service.TagApiDeploymentRevisionRequest], - Union[ - registry_models.ApiDeployment, - Awaitable[registry_models.ApiDeployment] - ]]: - raise NotImplementedError() - - @property - def list_api_deployment_revisions(self) -> Callable[ - [registry_service.ListApiDeploymentRevisionsRequest], - Union[ - registry_service.ListApiDeploymentRevisionsResponse, - Awaitable[registry_service.ListApiDeploymentRevisionsResponse] - ]]: - raise NotImplementedError() - - @property - def rollback_api_deployment(self) -> Callable[ - [registry_service.RollbackApiDeploymentRequest], - Union[ - registry_models.ApiDeployment, - Awaitable[registry_models.ApiDeployment] - ]]: - raise NotImplementedError() - - @property - def delete_api_deployment_revision(self) -> Callable[ - [registry_service.DeleteApiDeploymentRevisionRequest], - Union[ - registry_models.ApiDeployment, - Awaitable[registry_models.ApiDeployment] - ]]: - raise NotImplementedError() - - @property - def list_artifacts(self) -> Callable[ - [registry_service.ListArtifactsRequest], - Union[ - registry_service.ListArtifactsResponse, - Awaitable[registry_service.ListArtifactsResponse] - ]]: - raise NotImplementedError() - - @property - def get_artifact(self) -> Callable[ - [registry_service.GetArtifactRequest], - Union[ - registry_models.Artifact, - Awaitable[registry_models.Artifact] - ]]: - raise NotImplementedError() - - @property - def get_artifact_contents(self) -> Callable[ - [registry_service.GetArtifactContentsRequest], - Union[ - httpbody_pb2.HttpBody, - Awaitable[httpbody_pb2.HttpBody] - ]]: - raise NotImplementedError() - - @property - def create_artifact(self) -> Callable[ - [registry_service.CreateArtifactRequest], - Union[ - registry_models.Artifact, - Awaitable[registry_models.Artifact] - ]]: - raise NotImplementedError() - - @property - def replace_artifact(self) -> Callable[ - [registry_service.ReplaceArtifactRequest], - Union[ - registry_models.Artifact, - Awaitable[registry_models.Artifact] - ]]: - raise NotImplementedError() - - @property - def delete_artifact(self) -> Callable[ - [registry_service.DeleteArtifactRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - 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 set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - 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() - - -__all__ = ( - 'RegistryTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py deleted file mode 100644 index c98f6da..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc.py +++ /dev/null @@ -1,1362 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import grpc_helpers -from google.api_core import gapic_v1 -import google.auth # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service -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 empty_pb2 # type: ignore -from .base import RegistryTransport, DEFAULT_CLIENT_INFO - - -class RegistryGrpcTransport(RegistryTransport): - """gRPC backend transport for Registry. - - The Registry service allows teams to manage descriptions of - APIs. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - _stubs: Dict[str, Callable] - - def __init__(self, *, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def list_apis(self) -> Callable[ - [registry_service.ListApisRequest], - registry_service.ListApisResponse]: - r"""Return a callable for the list apis method over gRPC. - - Returns matching APIs. - - Returns: - Callable[[~.ListApisRequest], - ~.ListApisResponse]: - 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_apis' not in self._stubs: - self._stubs['list_apis'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApis', - request_serializer=registry_service.ListApisRequest.serialize, - response_deserializer=registry_service.ListApisResponse.deserialize, - ) - return self._stubs['list_apis'] - - @property - def get_api(self) -> Callable[ - [registry_service.GetApiRequest], - registry_models.Api]: - r"""Return a callable for the get api method over gRPC. - - Returns a specified API. - - Returns: - Callable[[~.GetApiRequest], - ~.Api]: - 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_api' not in self._stubs: - self._stubs['get_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApi', - request_serializer=registry_service.GetApiRequest.serialize, - response_deserializer=registry_models.Api.deserialize, - ) - return self._stubs['get_api'] - - @property - def create_api(self) -> Callable[ - [registry_service.CreateApiRequest], - registry_models.Api]: - r"""Return a callable for the create api method over gRPC. - - Creates a specified API. - - Returns: - Callable[[~.CreateApiRequest], - ~.Api]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api' not in self._stubs: - self._stubs['create_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApi', - request_serializer=registry_service.CreateApiRequest.serialize, - response_deserializer=registry_models.Api.deserialize, - ) - return self._stubs['create_api'] - - @property - def update_api(self) -> Callable[ - [registry_service.UpdateApiRequest], - registry_models.Api]: - r"""Return a callable for the update api method over gRPC. - - Used to modify a specified API. - - Returns: - Callable[[~.UpdateApiRequest], - ~.Api]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api' not in self._stubs: - self._stubs['update_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApi', - request_serializer=registry_service.UpdateApiRequest.serialize, - response_deserializer=registry_models.Api.deserialize, - ) - return self._stubs['update_api'] - - @property - def delete_api(self) -> Callable[ - [registry_service.DeleteApiRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete api method over gRPC. - - Removes a specified API and all of the resources that - it owns. - - Returns: - Callable[[~.DeleteApiRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api' not in self._stubs: - self._stubs['delete_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApi', - request_serializer=registry_service.DeleteApiRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api'] - - @property - def list_api_versions(self) -> Callable[ - [registry_service.ListApiVersionsRequest], - registry_service.ListApiVersionsResponse]: - r"""Return a callable for the list api versions method over gRPC. - - Returns matching versions. - - Returns: - Callable[[~.ListApiVersionsRequest], - ~.ListApiVersionsResponse]: - 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_api_versions' not in self._stubs: - self._stubs['list_api_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiVersions', - request_serializer=registry_service.ListApiVersionsRequest.serialize, - response_deserializer=registry_service.ListApiVersionsResponse.deserialize, - ) - return self._stubs['list_api_versions'] - - @property - def get_api_version(self) -> Callable[ - [registry_service.GetApiVersionRequest], - registry_models.ApiVersion]: - r"""Return a callable for the get api version method over gRPC. - - Returns a specified version. - - Returns: - Callable[[~.GetApiVersionRequest], - ~.ApiVersion]: - 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_api_version' not in self._stubs: - self._stubs['get_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiVersion', - request_serializer=registry_service.GetApiVersionRequest.serialize, - response_deserializer=registry_models.ApiVersion.deserialize, - ) - return self._stubs['get_api_version'] - - @property - def create_api_version(self) -> Callable[ - [registry_service.CreateApiVersionRequest], - registry_models.ApiVersion]: - r"""Return a callable for the create api version method over gRPC. - - Creates a specified version. - - Returns: - Callable[[~.CreateApiVersionRequest], - ~.ApiVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api_version' not in self._stubs: - self._stubs['create_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApiVersion', - request_serializer=registry_service.CreateApiVersionRequest.serialize, - response_deserializer=registry_models.ApiVersion.deserialize, - ) - return self._stubs['create_api_version'] - - @property - def update_api_version(self) -> Callable[ - [registry_service.UpdateApiVersionRequest], - registry_models.ApiVersion]: - r"""Return a callable for the update api version method over gRPC. - - Used to modify a specified version. - - Returns: - Callable[[~.UpdateApiVersionRequest], - ~.ApiVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api_version' not in self._stubs: - self._stubs['update_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApiVersion', - request_serializer=registry_service.UpdateApiVersionRequest.serialize, - response_deserializer=registry_models.ApiVersion.deserialize, - ) - return self._stubs['update_api_version'] - - @property - def delete_api_version(self) -> Callable[ - [registry_service.DeleteApiVersionRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete api version method over gRPC. - - Removes a specified version and all of the resources - that it owns. - - Returns: - Callable[[~.DeleteApiVersionRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_version' not in self._stubs: - self._stubs['delete_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiVersion', - request_serializer=registry_service.DeleteApiVersionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api_version'] - - @property - def list_api_specs(self) -> Callable[ - [registry_service.ListApiSpecsRequest], - registry_service.ListApiSpecsResponse]: - r"""Return a callable for the list api specs method over gRPC. - - Returns matching specs. - - Returns: - Callable[[~.ListApiSpecsRequest], - ~.ListApiSpecsResponse]: - 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_api_specs' not in self._stubs: - self._stubs['list_api_specs'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecs', - request_serializer=registry_service.ListApiSpecsRequest.serialize, - response_deserializer=registry_service.ListApiSpecsResponse.deserialize, - ) - return self._stubs['list_api_specs'] - - @property - def get_api_spec(self) -> Callable[ - [registry_service.GetApiSpecRequest], - registry_models.ApiSpec]: - r"""Return a callable for the get api spec method over gRPC. - - Returns a specified spec. - - Returns: - Callable[[~.GetApiSpecRequest], - ~.ApiSpec]: - 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_api_spec' not in self._stubs: - self._stubs['get_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiSpec', - request_serializer=registry_service.GetApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['get_api_spec'] - - @property - def get_api_spec_contents(self) -> Callable[ - [registry_service.GetApiSpecContentsRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the get api spec contents method over gRPC. - - Returns the contents of a specified spec. If specs are stored - with GZip compression, the default behavior is to return the - spec uncompressed (the mime_type response field indicates the - exact format returned). - - Returns: - Callable[[~.GetApiSpecContentsRequest], - ~.HttpBody]: - 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_api_spec_contents' not in self._stubs: - self._stubs['get_api_spec_contents'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiSpecContents', - request_serializer=registry_service.GetApiSpecContentsRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['get_api_spec_contents'] - - @property - def create_api_spec(self) -> Callable[ - [registry_service.CreateApiSpecRequest], - registry_models.ApiSpec]: - r"""Return a callable for the create api spec method over gRPC. - - Creates a specified spec. - - Returns: - Callable[[~.CreateApiSpecRequest], - ~.ApiSpec]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api_spec' not in self._stubs: - self._stubs['create_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApiSpec', - request_serializer=registry_service.CreateApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['create_api_spec'] - - @property - def update_api_spec(self) -> Callable[ - [registry_service.UpdateApiSpecRequest], - registry_models.ApiSpec]: - r"""Return a callable for the update api spec method over gRPC. - - Used to modify a specified spec. - - Returns: - Callable[[~.UpdateApiSpecRequest], - ~.ApiSpec]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api_spec' not in self._stubs: - self._stubs['update_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApiSpec', - request_serializer=registry_service.UpdateApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['update_api_spec'] - - @property - def delete_api_spec(self) -> Callable[ - [registry_service.DeleteApiSpecRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete api spec method over gRPC. - - Removes a specified spec, all revisions, and all - child resources (e.g., artifacts). - - Returns: - Callable[[~.DeleteApiSpecRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_spec' not in self._stubs: - self._stubs['delete_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpec', - request_serializer=registry_service.DeleteApiSpecRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api_spec'] - - @property - def tag_api_spec_revision(self) -> Callable[ - [registry_service.TagApiSpecRevisionRequest], - registry_models.ApiSpec]: - r"""Return a callable for the tag api spec revision method over gRPC. - - Adds a tag to a specified revision of a spec. - - Returns: - Callable[[~.TagApiSpecRevisionRequest], - ~.ApiSpec]: - 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 'tag_api_spec_revision' not in self._stubs: - self._stubs['tag_api_spec_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/TagApiSpecRevision', - request_serializer=registry_service.TagApiSpecRevisionRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['tag_api_spec_revision'] - - @property - def list_api_spec_revisions(self) -> Callable[ - [registry_service.ListApiSpecRevisionsRequest], - registry_service.ListApiSpecRevisionsResponse]: - r"""Return a callable for the list api spec revisions method over gRPC. - - Lists all revisions of a spec. - Revisions are returned in descending order of revision - creation time. - - Returns: - Callable[[~.ListApiSpecRevisionsRequest], - ~.ListApiSpecRevisionsResponse]: - 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_api_spec_revisions' not in self._stubs: - self._stubs['list_api_spec_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecRevisions', - request_serializer=registry_service.ListApiSpecRevisionsRequest.serialize, - response_deserializer=registry_service.ListApiSpecRevisionsResponse.deserialize, - ) - return self._stubs['list_api_spec_revisions'] - - @property - def rollback_api_spec(self) -> Callable[ - [registry_service.RollbackApiSpecRequest], - registry_models.ApiSpec]: - r"""Return a callable for the rollback api spec method over gRPC. - - Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - Returns: - Callable[[~.RollbackApiSpecRequest], - ~.ApiSpec]: - 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 'rollback_api_spec' not in self._stubs: - self._stubs['rollback_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/RollbackApiSpec', - request_serializer=registry_service.RollbackApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['rollback_api_spec'] - - @property - def delete_api_spec_revision(self) -> Callable[ - [registry_service.DeleteApiSpecRevisionRequest], - registry_models.ApiSpec]: - r"""Return a callable for the delete api spec revision method over gRPC. - - Deletes a revision of a spec. - - Returns: - Callable[[~.DeleteApiSpecRevisionRequest], - ~.ApiSpec]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_spec_revision' not in self._stubs: - self._stubs['delete_api_spec_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpecRevision', - request_serializer=registry_service.DeleteApiSpecRevisionRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['delete_api_spec_revision'] - - @property - def list_api_deployments(self) -> Callable[ - [registry_service.ListApiDeploymentsRequest], - registry_service.ListApiDeploymentsResponse]: - r"""Return a callable for the list api deployments method over gRPC. - - Returns matching deployments. - - Returns: - Callable[[~.ListApiDeploymentsRequest], - ~.ListApiDeploymentsResponse]: - 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_api_deployments' not in self._stubs: - self._stubs['list_api_deployments'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiDeployments', - request_serializer=registry_service.ListApiDeploymentsRequest.serialize, - response_deserializer=registry_service.ListApiDeploymentsResponse.deserialize, - ) - return self._stubs['list_api_deployments'] - - @property - def get_api_deployment(self) -> Callable[ - [registry_service.GetApiDeploymentRequest], - registry_models.ApiDeployment]: - r"""Return a callable for the get api deployment method over gRPC. - - Returns a specified deployment. - - Returns: - Callable[[~.GetApiDeploymentRequest], - ~.ApiDeployment]: - 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_api_deployment' not in self._stubs: - self._stubs['get_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiDeployment', - request_serializer=registry_service.GetApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['get_api_deployment'] - - @property - def create_api_deployment(self) -> Callable[ - [registry_service.CreateApiDeploymentRequest], - registry_models.ApiDeployment]: - r"""Return a callable for the create api deployment method over gRPC. - - Creates a specified deployment. - - Returns: - Callable[[~.CreateApiDeploymentRequest], - ~.ApiDeployment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api_deployment' not in self._stubs: - self._stubs['create_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApiDeployment', - request_serializer=registry_service.CreateApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['create_api_deployment'] - - @property - def update_api_deployment(self) -> Callable[ - [registry_service.UpdateApiDeploymentRequest], - registry_models.ApiDeployment]: - r"""Return a callable for the update api deployment method over gRPC. - - Used to modify a specified deployment. - - Returns: - Callable[[~.UpdateApiDeploymentRequest], - ~.ApiDeployment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api_deployment' not in self._stubs: - self._stubs['update_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApiDeployment', - request_serializer=registry_service.UpdateApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['update_api_deployment'] - - @property - def delete_api_deployment(self) -> Callable[ - [registry_service.DeleteApiDeploymentRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete api deployment method over gRPC. - - Removes a specified deployment, all revisions, and - all child resources (e.g., artifacts). - - Returns: - Callable[[~.DeleteApiDeploymentRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_deployment' not in self._stubs: - self._stubs['delete_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeployment', - request_serializer=registry_service.DeleteApiDeploymentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api_deployment'] - - @property - def tag_api_deployment_revision(self) -> Callable[ - [registry_service.TagApiDeploymentRevisionRequest], - registry_models.ApiDeployment]: - r"""Return a callable for the tag api deployment revision method over gRPC. - - Adds a tag to a specified revision of a - deployment. - - Returns: - Callable[[~.TagApiDeploymentRevisionRequest], - ~.ApiDeployment]: - 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 'tag_api_deployment_revision' not in self._stubs: - self._stubs['tag_api_deployment_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/TagApiDeploymentRevision', - request_serializer=registry_service.TagApiDeploymentRevisionRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['tag_api_deployment_revision'] - - @property - def list_api_deployment_revisions(self) -> Callable[ - [registry_service.ListApiDeploymentRevisionsRequest], - registry_service.ListApiDeploymentRevisionsResponse]: - r"""Return a callable for the list api deployment revisions method over gRPC. - - Lists all revisions of a deployment. - Revisions are returned in descending order of revision - creation time. - - Returns: - Callable[[~.ListApiDeploymentRevisionsRequest], - ~.ListApiDeploymentRevisionsResponse]: - 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_api_deployment_revisions' not in self._stubs: - self._stubs['list_api_deployment_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiDeploymentRevisions', - request_serializer=registry_service.ListApiDeploymentRevisionsRequest.serialize, - response_deserializer=registry_service.ListApiDeploymentRevisionsResponse.deserialize, - ) - return self._stubs['list_api_deployment_revisions'] - - @property - def rollback_api_deployment(self) -> Callable[ - [registry_service.RollbackApiDeploymentRequest], - registry_models.ApiDeployment]: - r"""Return a callable for the rollback api deployment method over gRPC. - - Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - Returns: - Callable[[~.RollbackApiDeploymentRequest], - ~.ApiDeployment]: - 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 'rollback_api_deployment' not in self._stubs: - self._stubs['rollback_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/RollbackApiDeployment', - request_serializer=registry_service.RollbackApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['rollback_api_deployment'] - - @property - def delete_api_deployment_revision(self) -> Callable[ - [registry_service.DeleteApiDeploymentRevisionRequest], - registry_models.ApiDeployment]: - r"""Return a callable for the delete api deployment revision method over gRPC. - - Deletes a revision of a deployment. - - Returns: - Callable[[~.DeleteApiDeploymentRevisionRequest], - ~.ApiDeployment]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_deployment_revision' not in self._stubs: - self._stubs['delete_api_deployment_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeploymentRevision', - request_serializer=registry_service.DeleteApiDeploymentRevisionRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['delete_api_deployment_revision'] - - @property - def list_artifacts(self) -> Callable[ - [registry_service.ListArtifactsRequest], - registry_service.ListArtifactsResponse]: - r"""Return a callable for the list artifacts method over gRPC. - - Returns matching artifacts. - - Returns: - Callable[[~.ListArtifactsRequest], - ~.ListArtifactsResponse]: - 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_artifacts' not in self._stubs: - self._stubs['list_artifacts'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListArtifacts', - request_serializer=registry_service.ListArtifactsRequest.serialize, - response_deserializer=registry_service.ListArtifactsResponse.deserialize, - ) - return self._stubs['list_artifacts'] - - @property - def get_artifact(self) -> Callable[ - [registry_service.GetArtifactRequest], - registry_models.Artifact]: - r"""Return a callable for the get artifact method over gRPC. - - Returns a specified artifact. - - Returns: - Callable[[~.GetArtifactRequest], - ~.Artifact]: - 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_artifact' not in self._stubs: - self._stubs['get_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetArtifact', - request_serializer=registry_service.GetArtifactRequest.serialize, - response_deserializer=registry_models.Artifact.deserialize, - ) - return self._stubs['get_artifact'] - - @property - def get_artifact_contents(self) -> Callable[ - [registry_service.GetArtifactContentsRequest], - httpbody_pb2.HttpBody]: - r"""Return a callable for the get artifact contents method over gRPC. - - Returns the contents of a specified artifact. If artifacts are - stored with GZip compression, the default behavior is to return - the artifact uncompressed (the mime_type response field - indicates the exact format returned). - - Returns: - Callable[[~.GetArtifactContentsRequest], - ~.HttpBody]: - 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_artifact_contents' not in self._stubs: - self._stubs['get_artifact_contents'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetArtifactContents', - request_serializer=registry_service.GetArtifactContentsRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['get_artifact_contents'] - - @property - def create_artifact(self) -> Callable[ - [registry_service.CreateArtifactRequest], - registry_models.Artifact]: - r"""Return a callable for the create artifact method over gRPC. - - Creates a specified artifact. - - Returns: - Callable[[~.CreateArtifactRequest], - ~.Artifact]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_artifact' not in self._stubs: - self._stubs['create_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateArtifact', - request_serializer=registry_service.CreateArtifactRequest.serialize, - response_deserializer=registry_models.Artifact.deserialize, - ) - return self._stubs['create_artifact'] - - @property - def replace_artifact(self) -> Callable[ - [registry_service.ReplaceArtifactRequest], - registry_models.Artifact]: - r"""Return a callable for the replace artifact method over gRPC. - - Used to replace a specified artifact. - - Returns: - Callable[[~.ReplaceArtifactRequest], - ~.Artifact]: - 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 'replace_artifact' not in self._stubs: - self._stubs['replace_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ReplaceArtifact', - request_serializer=registry_service.ReplaceArtifactRequest.serialize, - response_deserializer=registry_models.Artifact.deserialize, - ) - return self._stubs['replace_artifact'] - - @property - def delete_artifact(self) -> Callable[ - [registry_service.DeleteArtifactRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete artifact method over gRPC. - - Removes a specified artifact. - - Returns: - Callable[[~.DeleteArtifactRequest], - ~.Empty]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_artifact' not in self._stubs: - self._stubs['delete_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteArtifact', - request_serializer=registry_service.DeleteArtifactRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_artifact'] - - 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 set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'RegistryGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py deleted file mode 100644 index 669459a..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/grpc_asyncio.py +++ /dev/null @@ -1,1361 +0,0 @@ -# -*- 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. -# -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service -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 empty_pb2 # type: ignore -from .base import RegistryTransport, DEFAULT_CLIENT_INFO -from .grpc import RegistryGrpcTransport - - -class RegistryGrpcAsyncIOTransport(RegistryTransport): - """gRPC AsyncIO backend transport for Registry. - - The Registry service allows teams to manage descriptions of - APIs. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel(cls, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if channel: - # Ignore credentials if a channel was passed. - credentials = False - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def list_apis(self) -> Callable[ - [registry_service.ListApisRequest], - Awaitable[registry_service.ListApisResponse]]: - r"""Return a callable for the list apis method over gRPC. - - Returns matching APIs. - - Returns: - Callable[[~.ListApisRequest], - Awaitable[~.ListApisResponse]]: - 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_apis' not in self._stubs: - self._stubs['list_apis'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApis', - request_serializer=registry_service.ListApisRequest.serialize, - response_deserializer=registry_service.ListApisResponse.deserialize, - ) - return self._stubs['list_apis'] - - @property - def get_api(self) -> Callable[ - [registry_service.GetApiRequest], - Awaitable[registry_models.Api]]: - r"""Return a callable for the get api method over gRPC. - - Returns a specified API. - - Returns: - Callable[[~.GetApiRequest], - Awaitable[~.Api]]: - 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_api' not in self._stubs: - self._stubs['get_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApi', - request_serializer=registry_service.GetApiRequest.serialize, - response_deserializer=registry_models.Api.deserialize, - ) - return self._stubs['get_api'] - - @property - def create_api(self) -> Callable[ - [registry_service.CreateApiRequest], - Awaitable[registry_models.Api]]: - r"""Return a callable for the create api method over gRPC. - - Creates a specified API. - - Returns: - Callable[[~.CreateApiRequest], - Awaitable[~.Api]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api' not in self._stubs: - self._stubs['create_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApi', - request_serializer=registry_service.CreateApiRequest.serialize, - response_deserializer=registry_models.Api.deserialize, - ) - return self._stubs['create_api'] - - @property - def update_api(self) -> Callable[ - [registry_service.UpdateApiRequest], - Awaitable[registry_models.Api]]: - r"""Return a callable for the update api method over gRPC. - - Used to modify a specified API. - - Returns: - Callable[[~.UpdateApiRequest], - Awaitable[~.Api]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api' not in self._stubs: - self._stubs['update_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApi', - request_serializer=registry_service.UpdateApiRequest.serialize, - response_deserializer=registry_models.Api.deserialize, - ) - return self._stubs['update_api'] - - @property - def delete_api(self) -> Callable[ - [registry_service.DeleteApiRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete api method over gRPC. - - Removes a specified API and all of the resources that - it owns. - - Returns: - Callable[[~.DeleteApiRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api' not in self._stubs: - self._stubs['delete_api'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApi', - request_serializer=registry_service.DeleteApiRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api'] - - @property - def list_api_versions(self) -> Callable[ - [registry_service.ListApiVersionsRequest], - Awaitable[registry_service.ListApiVersionsResponse]]: - r"""Return a callable for the list api versions method over gRPC. - - Returns matching versions. - - Returns: - Callable[[~.ListApiVersionsRequest], - Awaitable[~.ListApiVersionsResponse]]: - 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_api_versions' not in self._stubs: - self._stubs['list_api_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiVersions', - request_serializer=registry_service.ListApiVersionsRequest.serialize, - response_deserializer=registry_service.ListApiVersionsResponse.deserialize, - ) - return self._stubs['list_api_versions'] - - @property - def get_api_version(self) -> Callable[ - [registry_service.GetApiVersionRequest], - Awaitable[registry_models.ApiVersion]]: - r"""Return a callable for the get api version method over gRPC. - - Returns a specified version. - - Returns: - Callable[[~.GetApiVersionRequest], - Awaitable[~.ApiVersion]]: - 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_api_version' not in self._stubs: - self._stubs['get_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiVersion', - request_serializer=registry_service.GetApiVersionRequest.serialize, - response_deserializer=registry_models.ApiVersion.deserialize, - ) - return self._stubs['get_api_version'] - - @property - def create_api_version(self) -> Callable[ - [registry_service.CreateApiVersionRequest], - Awaitable[registry_models.ApiVersion]]: - r"""Return a callable for the create api version method over gRPC. - - Creates a specified version. - - Returns: - Callable[[~.CreateApiVersionRequest], - Awaitable[~.ApiVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api_version' not in self._stubs: - self._stubs['create_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApiVersion', - request_serializer=registry_service.CreateApiVersionRequest.serialize, - response_deserializer=registry_models.ApiVersion.deserialize, - ) - return self._stubs['create_api_version'] - - @property - def update_api_version(self) -> Callable[ - [registry_service.UpdateApiVersionRequest], - Awaitable[registry_models.ApiVersion]]: - r"""Return a callable for the update api version method over gRPC. - - Used to modify a specified version. - - Returns: - Callable[[~.UpdateApiVersionRequest], - Awaitable[~.ApiVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api_version' not in self._stubs: - self._stubs['update_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApiVersion', - request_serializer=registry_service.UpdateApiVersionRequest.serialize, - response_deserializer=registry_models.ApiVersion.deserialize, - ) - return self._stubs['update_api_version'] - - @property - def delete_api_version(self) -> Callable[ - [registry_service.DeleteApiVersionRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete api version method over gRPC. - - Removes a specified version and all of the resources - that it owns. - - Returns: - Callable[[~.DeleteApiVersionRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_version' not in self._stubs: - self._stubs['delete_api_version'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiVersion', - request_serializer=registry_service.DeleteApiVersionRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api_version'] - - @property - def list_api_specs(self) -> Callable[ - [registry_service.ListApiSpecsRequest], - Awaitable[registry_service.ListApiSpecsResponse]]: - r"""Return a callable for the list api specs method over gRPC. - - Returns matching specs. - - Returns: - Callable[[~.ListApiSpecsRequest], - Awaitable[~.ListApiSpecsResponse]]: - 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_api_specs' not in self._stubs: - self._stubs['list_api_specs'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecs', - request_serializer=registry_service.ListApiSpecsRequest.serialize, - response_deserializer=registry_service.ListApiSpecsResponse.deserialize, - ) - return self._stubs['list_api_specs'] - - @property - def get_api_spec(self) -> Callable[ - [registry_service.GetApiSpecRequest], - Awaitable[registry_models.ApiSpec]]: - r"""Return a callable for the get api spec method over gRPC. - - Returns a specified spec. - - Returns: - Callable[[~.GetApiSpecRequest], - Awaitable[~.ApiSpec]]: - 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_api_spec' not in self._stubs: - self._stubs['get_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiSpec', - request_serializer=registry_service.GetApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['get_api_spec'] - - @property - def get_api_spec_contents(self) -> Callable[ - [registry_service.GetApiSpecContentsRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the get api spec contents method over gRPC. - - Returns the contents of a specified spec. If specs are stored - with GZip compression, the default behavior is to return the - spec uncompressed (the mime_type response field indicates the - exact format returned). - - Returns: - Callable[[~.GetApiSpecContentsRequest], - Awaitable[~.HttpBody]]: - 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_api_spec_contents' not in self._stubs: - self._stubs['get_api_spec_contents'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiSpecContents', - request_serializer=registry_service.GetApiSpecContentsRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['get_api_spec_contents'] - - @property - def create_api_spec(self) -> Callable[ - [registry_service.CreateApiSpecRequest], - Awaitable[registry_models.ApiSpec]]: - r"""Return a callable for the create api spec method over gRPC. - - Creates a specified spec. - - Returns: - Callable[[~.CreateApiSpecRequest], - Awaitable[~.ApiSpec]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api_spec' not in self._stubs: - self._stubs['create_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApiSpec', - request_serializer=registry_service.CreateApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['create_api_spec'] - - @property - def update_api_spec(self) -> Callable[ - [registry_service.UpdateApiSpecRequest], - Awaitable[registry_models.ApiSpec]]: - r"""Return a callable for the update api spec method over gRPC. - - Used to modify a specified spec. - - Returns: - Callable[[~.UpdateApiSpecRequest], - Awaitable[~.ApiSpec]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api_spec' not in self._stubs: - self._stubs['update_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApiSpec', - request_serializer=registry_service.UpdateApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['update_api_spec'] - - @property - def delete_api_spec(self) -> Callable[ - [registry_service.DeleteApiSpecRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete api spec method over gRPC. - - Removes a specified spec, all revisions, and all - child resources (e.g., artifacts). - - Returns: - Callable[[~.DeleteApiSpecRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_spec' not in self._stubs: - self._stubs['delete_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpec', - request_serializer=registry_service.DeleteApiSpecRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api_spec'] - - @property - def tag_api_spec_revision(self) -> Callable[ - [registry_service.TagApiSpecRevisionRequest], - Awaitable[registry_models.ApiSpec]]: - r"""Return a callable for the tag api spec revision method over gRPC. - - Adds a tag to a specified revision of a spec. - - Returns: - Callable[[~.TagApiSpecRevisionRequest], - Awaitable[~.ApiSpec]]: - 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 'tag_api_spec_revision' not in self._stubs: - self._stubs['tag_api_spec_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/TagApiSpecRevision', - request_serializer=registry_service.TagApiSpecRevisionRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['tag_api_spec_revision'] - - @property - def list_api_spec_revisions(self) -> Callable[ - [registry_service.ListApiSpecRevisionsRequest], - Awaitable[registry_service.ListApiSpecRevisionsResponse]]: - r"""Return a callable for the list api spec revisions method over gRPC. - - Lists all revisions of a spec. - Revisions are returned in descending order of revision - creation time. - - Returns: - Callable[[~.ListApiSpecRevisionsRequest], - Awaitable[~.ListApiSpecRevisionsResponse]]: - 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_api_spec_revisions' not in self._stubs: - self._stubs['list_api_spec_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiSpecRevisions', - request_serializer=registry_service.ListApiSpecRevisionsRequest.serialize, - response_deserializer=registry_service.ListApiSpecRevisionsResponse.deserialize, - ) - return self._stubs['list_api_spec_revisions'] - - @property - def rollback_api_spec(self) -> Callable[ - [registry_service.RollbackApiSpecRequest], - Awaitable[registry_models.ApiSpec]]: - r"""Return a callable for the rollback api spec method over gRPC. - - Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - Returns: - Callable[[~.RollbackApiSpecRequest], - Awaitable[~.ApiSpec]]: - 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 'rollback_api_spec' not in self._stubs: - self._stubs['rollback_api_spec'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/RollbackApiSpec', - request_serializer=registry_service.RollbackApiSpecRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['rollback_api_spec'] - - @property - def delete_api_spec_revision(self) -> Callable[ - [registry_service.DeleteApiSpecRevisionRequest], - Awaitable[registry_models.ApiSpec]]: - r"""Return a callable for the delete api spec revision method over gRPC. - - Deletes a revision of a spec. - - Returns: - Callable[[~.DeleteApiSpecRevisionRequest], - Awaitable[~.ApiSpec]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_spec_revision' not in self._stubs: - self._stubs['delete_api_spec_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiSpecRevision', - request_serializer=registry_service.DeleteApiSpecRevisionRequest.serialize, - response_deserializer=registry_models.ApiSpec.deserialize, - ) - return self._stubs['delete_api_spec_revision'] - - @property - def list_api_deployments(self) -> Callable[ - [registry_service.ListApiDeploymentsRequest], - Awaitable[registry_service.ListApiDeploymentsResponse]]: - r"""Return a callable for the list api deployments method over gRPC. - - Returns matching deployments. - - Returns: - Callable[[~.ListApiDeploymentsRequest], - Awaitable[~.ListApiDeploymentsResponse]]: - 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_api_deployments' not in self._stubs: - self._stubs['list_api_deployments'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiDeployments', - request_serializer=registry_service.ListApiDeploymentsRequest.serialize, - response_deserializer=registry_service.ListApiDeploymentsResponse.deserialize, - ) - return self._stubs['list_api_deployments'] - - @property - def get_api_deployment(self) -> Callable[ - [registry_service.GetApiDeploymentRequest], - Awaitable[registry_models.ApiDeployment]]: - r"""Return a callable for the get api deployment method over gRPC. - - Returns a specified deployment. - - Returns: - Callable[[~.GetApiDeploymentRequest], - Awaitable[~.ApiDeployment]]: - 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_api_deployment' not in self._stubs: - self._stubs['get_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetApiDeployment', - request_serializer=registry_service.GetApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['get_api_deployment'] - - @property - def create_api_deployment(self) -> Callable[ - [registry_service.CreateApiDeploymentRequest], - Awaitable[registry_models.ApiDeployment]]: - r"""Return a callable for the create api deployment method over gRPC. - - Creates a specified deployment. - - Returns: - Callable[[~.CreateApiDeploymentRequest], - Awaitable[~.ApiDeployment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_api_deployment' not in self._stubs: - self._stubs['create_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateApiDeployment', - request_serializer=registry_service.CreateApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['create_api_deployment'] - - @property - def update_api_deployment(self) -> Callable[ - [registry_service.UpdateApiDeploymentRequest], - Awaitable[registry_models.ApiDeployment]]: - r"""Return a callable for the update api deployment method over gRPC. - - Used to modify a specified deployment. - - Returns: - Callable[[~.UpdateApiDeploymentRequest], - Awaitable[~.ApiDeployment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'update_api_deployment' not in self._stubs: - self._stubs['update_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/UpdateApiDeployment', - request_serializer=registry_service.UpdateApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['update_api_deployment'] - - @property - def delete_api_deployment(self) -> Callable[ - [registry_service.DeleteApiDeploymentRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete api deployment method over gRPC. - - Removes a specified deployment, all revisions, and - all child resources (e.g., artifacts). - - Returns: - Callable[[~.DeleteApiDeploymentRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_deployment' not in self._stubs: - self._stubs['delete_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeployment', - request_serializer=registry_service.DeleteApiDeploymentRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_api_deployment'] - - @property - def tag_api_deployment_revision(self) -> Callable[ - [registry_service.TagApiDeploymentRevisionRequest], - Awaitable[registry_models.ApiDeployment]]: - r"""Return a callable for the tag api deployment revision method over gRPC. - - Adds a tag to a specified revision of a - deployment. - - Returns: - Callable[[~.TagApiDeploymentRevisionRequest], - Awaitable[~.ApiDeployment]]: - 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 'tag_api_deployment_revision' not in self._stubs: - self._stubs['tag_api_deployment_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/TagApiDeploymentRevision', - request_serializer=registry_service.TagApiDeploymentRevisionRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['tag_api_deployment_revision'] - - @property - def list_api_deployment_revisions(self) -> Callable[ - [registry_service.ListApiDeploymentRevisionsRequest], - Awaitable[registry_service.ListApiDeploymentRevisionsResponse]]: - r"""Return a callable for the list api deployment revisions method over gRPC. - - Lists all revisions of a deployment. - Revisions are returned in descending order of revision - creation time. - - Returns: - Callable[[~.ListApiDeploymentRevisionsRequest], - Awaitable[~.ListApiDeploymentRevisionsResponse]]: - 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_api_deployment_revisions' not in self._stubs: - self._stubs['list_api_deployment_revisions'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListApiDeploymentRevisions', - request_serializer=registry_service.ListApiDeploymentRevisionsRequest.serialize, - response_deserializer=registry_service.ListApiDeploymentRevisionsResponse.deserialize, - ) - return self._stubs['list_api_deployment_revisions'] - - @property - def rollback_api_deployment(self) -> Callable[ - [registry_service.RollbackApiDeploymentRequest], - Awaitable[registry_models.ApiDeployment]]: - r"""Return a callable for the rollback api deployment method over gRPC. - - Sets the current revision to a specified prior - revision. Note that this creates a new revision with a - new revision ID. - - Returns: - Callable[[~.RollbackApiDeploymentRequest], - Awaitable[~.ApiDeployment]]: - 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 'rollback_api_deployment' not in self._stubs: - self._stubs['rollback_api_deployment'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/RollbackApiDeployment', - request_serializer=registry_service.RollbackApiDeploymentRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['rollback_api_deployment'] - - @property - def delete_api_deployment_revision(self) -> Callable[ - [registry_service.DeleteApiDeploymentRevisionRequest], - Awaitable[registry_models.ApiDeployment]]: - r"""Return a callable for the delete api deployment revision method over gRPC. - - Deletes a revision of a deployment. - - Returns: - Callable[[~.DeleteApiDeploymentRevisionRequest], - Awaitable[~.ApiDeployment]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_api_deployment_revision' not in self._stubs: - self._stubs['delete_api_deployment_revision'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteApiDeploymentRevision', - request_serializer=registry_service.DeleteApiDeploymentRevisionRequest.serialize, - response_deserializer=registry_models.ApiDeployment.deserialize, - ) - return self._stubs['delete_api_deployment_revision'] - - @property - def list_artifacts(self) -> Callable[ - [registry_service.ListArtifactsRequest], - Awaitable[registry_service.ListArtifactsResponse]]: - r"""Return a callable for the list artifacts method over gRPC. - - Returns matching artifacts. - - Returns: - Callable[[~.ListArtifactsRequest], - Awaitable[~.ListArtifactsResponse]]: - 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_artifacts' not in self._stubs: - self._stubs['list_artifacts'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ListArtifacts', - request_serializer=registry_service.ListArtifactsRequest.serialize, - response_deserializer=registry_service.ListArtifactsResponse.deserialize, - ) - return self._stubs['list_artifacts'] - - @property - def get_artifact(self) -> Callable[ - [registry_service.GetArtifactRequest], - Awaitable[registry_models.Artifact]]: - r"""Return a callable for the get artifact method over gRPC. - - Returns a specified artifact. - - Returns: - Callable[[~.GetArtifactRequest], - Awaitable[~.Artifact]]: - 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_artifact' not in self._stubs: - self._stubs['get_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetArtifact', - request_serializer=registry_service.GetArtifactRequest.serialize, - response_deserializer=registry_models.Artifact.deserialize, - ) - return self._stubs['get_artifact'] - - @property - def get_artifact_contents(self) -> Callable[ - [registry_service.GetArtifactContentsRequest], - Awaitable[httpbody_pb2.HttpBody]]: - r"""Return a callable for the get artifact contents method over gRPC. - - Returns the contents of a specified artifact. If artifacts are - stored with GZip compression, the default behavior is to return - the artifact uncompressed (the mime_type response field - indicates the exact format returned). - - Returns: - Callable[[~.GetArtifactContentsRequest], - Awaitable[~.HttpBody]]: - 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_artifact_contents' not in self._stubs: - self._stubs['get_artifact_contents'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/GetArtifactContents', - request_serializer=registry_service.GetArtifactContentsRequest.serialize, - response_deserializer=httpbody_pb2.HttpBody.FromString, - ) - return self._stubs['get_artifact_contents'] - - @property - def create_artifact(self) -> Callable[ - [registry_service.CreateArtifactRequest], - Awaitable[registry_models.Artifact]]: - r"""Return a callable for the create artifact method over gRPC. - - Creates a specified artifact. - - Returns: - Callable[[~.CreateArtifactRequest], - Awaitable[~.Artifact]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'create_artifact' not in self._stubs: - self._stubs['create_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/CreateArtifact', - request_serializer=registry_service.CreateArtifactRequest.serialize, - response_deserializer=registry_models.Artifact.deserialize, - ) - return self._stubs['create_artifact'] - - @property - def replace_artifact(self) -> Callable[ - [registry_service.ReplaceArtifactRequest], - Awaitable[registry_models.Artifact]]: - r"""Return a callable for the replace artifact method over gRPC. - - Used to replace a specified artifact. - - Returns: - Callable[[~.ReplaceArtifactRequest], - Awaitable[~.Artifact]]: - 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 'replace_artifact' not in self._stubs: - self._stubs['replace_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/ReplaceArtifact', - request_serializer=registry_service.ReplaceArtifactRequest.serialize, - response_deserializer=registry_models.Artifact.deserialize, - ) - return self._stubs['replace_artifact'] - - @property - def delete_artifact(self) -> Callable[ - [registry_service.DeleteArtifactRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete artifact method over gRPC. - - Removes a specified artifact. - - Returns: - Callable[[~.DeleteArtifactRequest], - Awaitable[~.Empty]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'delete_artifact' not in self._stubs: - self._stubs['delete_artifact'] = self.grpc_channel.unary_unary( - '/google.cloud.apigeeregistry.v1.Registry/DeleteArtifact', - request_serializer=registry_service.DeleteArtifactRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_artifact'] - - 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"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - -__all__ = ( - 'RegistryGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py deleted file mode 100644 index f57a8fa..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/services/registry/transports/rest.py +++ /dev/null @@ -1,5357 +0,0 @@ -# -*- 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. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -import grpc # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from google.longrunning import operations_pb2 -from requests import __version__ as requests_version -import dataclasses -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object] # type: ignore - - -from google.api import httpbody_pb2 # type: ignore -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service -from google.protobuf import empty_pb2 # type: ignore - -from .base import RegistryTransport, DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=requests_version, -) - - -class RegistryRestInterceptor: - """Interceptor for Registry. - - Interceptors are used to manipulate requests, request metadata, and responses - in arbitrary ways. - Example use cases include: - * Logging - * Verifying requests according to service or custom semantics - * Stripping extraneous information from responses - - These use cases and more can be enabled by injecting an - instance of a custom subclass when constructing the RegistryRestTransport. - - .. code-block:: python - class MyCustomRegistryInterceptor(RegistryRestInterceptor): - def pre_create_api(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_api(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_api_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_api_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_api_spec(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_api_spec(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_api_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_api_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_artifact(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_artifact(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_api(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_api_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_api_deployment_revision(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_api_deployment_revision(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_api_spec(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_api_spec_revision(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_delete_api_spec_revision(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_api_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_artifact(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_api(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_api(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_api_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_api_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_api_spec(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_api_spec(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_api_spec_contents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_api_spec_contents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_api_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_api_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_artifact(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_artifact(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_artifact_contents(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_artifact_contents(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_api_deployment_revisions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_api_deployment_revisions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_api_deployments(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_api_deployments(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_apis(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_apis(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_api_spec_revisions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_api_spec_revisions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_api_specs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_api_specs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_api_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_api_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_artifacts(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_artifacts(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_replace_artifact(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_replace_artifact(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_rollback_api_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_rollback_api_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_rollback_api_spec(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_rollback_api_spec(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_tag_api_deployment_revision(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_tag_api_deployment_revision(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_tag_api_spec_revision(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_tag_api_spec_revision(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_api(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_api(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_api_deployment(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_api_deployment(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_api_spec(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_api_spec(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_api_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_api_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = RegistryRestTransport(interceptor=MyCustomRegistryInterceptor()) - client = RegistryClient(transport=transport) - - - """ - def pre_create_api(self, request: registry_service.CreateApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_api - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_create_api(self, response: registry_models.Api) -> registry_models.Api: - """Post-rpc interceptor for create_api - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_create_api_deployment(self, request: registry_service.CreateApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiDeploymentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_api_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_create_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: - """Post-rpc interceptor for create_api_deployment - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_create_api_spec(self, request: registry_service.CreateApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiSpecRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_api_spec - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_create_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: - """Post-rpc interceptor for create_api_spec - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_create_api_version(self, request: registry_service.CreateApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateApiVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_api_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_create_api_version(self, response: registry_models.ApiVersion) -> registry_models.ApiVersion: - """Post-rpc interceptor for create_api_version - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_create_artifact(self, request: registry_service.CreateArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.CreateArtifactRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_artifact - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_create_artifact(self, response: registry_models.Artifact) -> registry_models.Artifact: - """Post-rpc interceptor for create_artifact - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_delete_api(self, request: registry_service.DeleteApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_api - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def pre_delete_api_deployment(self, request: registry_service.DeleteApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiDeploymentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_api_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def pre_delete_api_deployment_revision(self, request: registry_service.DeleteApiDeploymentRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiDeploymentRevisionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_api_deployment_revision - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_delete_api_deployment_revision(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: - """Post-rpc interceptor for delete_api_deployment_revision - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_delete_api_spec(self, request: registry_service.DeleteApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiSpecRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_api_spec - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def pre_delete_api_spec_revision(self, request: registry_service.DeleteApiSpecRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiSpecRevisionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_api_spec_revision - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_delete_api_spec_revision(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: - """Post-rpc interceptor for delete_api_spec_revision - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_delete_api_version(self, request: registry_service.DeleteApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteApiVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_api_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def pre_delete_artifact(self, request: registry_service.DeleteArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.DeleteArtifactRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_artifact - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def pre_get_api(self, request: registry_service.GetApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_api - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_api(self, response: registry_models.Api) -> registry_models.Api: - """Post-rpc interceptor for get_api - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_api_deployment(self, request: registry_service.GetApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiDeploymentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_api_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: - """Post-rpc interceptor for get_api_deployment - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_api_spec(self, request: registry_service.GetApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiSpecRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_api_spec - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: - """Post-rpc interceptor for get_api_spec - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_api_spec_contents(self, request: registry_service.GetApiSpecContentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiSpecContentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_api_spec_contents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_api_spec_contents(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: - """Post-rpc interceptor for get_api_spec_contents - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_api_version(self, request: registry_service.GetApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetApiVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_api_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_api_version(self, response: registry_models.ApiVersion) -> registry_models.ApiVersion: - """Post-rpc interceptor for get_api_version - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_artifact(self, request: registry_service.GetArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetArtifactRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_artifact - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_artifact(self, response: registry_models.Artifact) -> registry_models.Artifact: - """Post-rpc interceptor for get_artifact - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_artifact_contents(self, request: registry_service.GetArtifactContentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.GetArtifactContentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_artifact_contents - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_artifact_contents(self, response: httpbody_pb2.HttpBody) -> httpbody_pb2.HttpBody: - """Post-rpc interceptor for get_artifact_contents - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_api_deployment_revisions(self, request: registry_service.ListApiDeploymentRevisionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiDeploymentRevisionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_api_deployment_revisions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_api_deployment_revisions(self, response: registry_service.ListApiDeploymentRevisionsResponse) -> registry_service.ListApiDeploymentRevisionsResponse: - """Post-rpc interceptor for list_api_deployment_revisions - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_api_deployments(self, request: registry_service.ListApiDeploymentsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiDeploymentsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_api_deployments - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_api_deployments(self, response: registry_service.ListApiDeploymentsResponse) -> registry_service.ListApiDeploymentsResponse: - """Post-rpc interceptor for list_api_deployments - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_apis(self, request: registry_service.ListApisRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApisRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_apis - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_apis(self, response: registry_service.ListApisResponse) -> registry_service.ListApisResponse: - """Post-rpc interceptor for list_apis - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_api_spec_revisions(self, request: registry_service.ListApiSpecRevisionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiSpecRevisionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_api_spec_revisions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_api_spec_revisions(self, response: registry_service.ListApiSpecRevisionsResponse) -> registry_service.ListApiSpecRevisionsResponse: - """Post-rpc interceptor for list_api_spec_revisions - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_api_specs(self, request: registry_service.ListApiSpecsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiSpecsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_api_specs - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_api_specs(self, response: registry_service.ListApiSpecsResponse) -> registry_service.ListApiSpecsResponse: - """Post-rpc interceptor for list_api_specs - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_api_versions(self, request: registry_service.ListApiVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListApiVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_api_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_api_versions(self, response: registry_service.ListApiVersionsResponse) -> registry_service.ListApiVersionsResponse: - """Post-rpc interceptor for list_api_versions - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_artifacts(self, request: registry_service.ListArtifactsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ListArtifactsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_artifacts - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_artifacts(self, response: registry_service.ListArtifactsResponse) -> registry_service.ListArtifactsResponse: - """Post-rpc interceptor for list_artifacts - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_replace_artifact(self, request: registry_service.ReplaceArtifactRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.ReplaceArtifactRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for replace_artifact - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_replace_artifact(self, response: registry_models.Artifact) -> registry_models.Artifact: - """Post-rpc interceptor for replace_artifact - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_rollback_api_deployment(self, request: registry_service.RollbackApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.RollbackApiDeploymentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for rollback_api_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_rollback_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: - """Post-rpc interceptor for rollback_api_deployment - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_rollback_api_spec(self, request: registry_service.RollbackApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.RollbackApiSpecRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for rollback_api_spec - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_rollback_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: - """Post-rpc interceptor for rollback_api_spec - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_tag_api_deployment_revision(self, request: registry_service.TagApiDeploymentRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.TagApiDeploymentRevisionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for tag_api_deployment_revision - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_tag_api_deployment_revision(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: - """Post-rpc interceptor for tag_api_deployment_revision - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_tag_api_spec_revision(self, request: registry_service.TagApiSpecRevisionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.TagApiSpecRevisionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for tag_api_spec_revision - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_tag_api_spec_revision(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: - """Post-rpc interceptor for tag_api_spec_revision - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_update_api(self, request: registry_service.UpdateApiRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_api - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_update_api(self, response: registry_models.Api) -> registry_models.Api: - """Post-rpc interceptor for update_api - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_update_api_deployment(self, request: registry_service.UpdateApiDeploymentRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiDeploymentRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_api_deployment - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_update_api_deployment(self, response: registry_models.ApiDeployment) -> registry_models.ApiDeployment: - """Post-rpc interceptor for update_api_deployment - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_update_api_spec(self, request: registry_service.UpdateApiSpecRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiSpecRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_api_spec - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_update_api_spec(self, response: registry_models.ApiSpec) -> registry_models.ApiSpec: - """Post-rpc interceptor for update_api_spec - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_update_api_version(self, request: registry_service.UpdateApiVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[registry_service.UpdateApiVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_api_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_update_api_version(self, response: registry_models.ApiVersion) -> registry_models.ApiVersion: - """Post-rpc interceptor for update_api_version - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_cancel_operation( - self, request: operations_pb2.CancelOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.CancelOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_cancel_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for cancel_operation - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_delete_operation( - self, request: operations_pb2.DeleteOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_delete_operation( - self, response: None - ) -> None: - """Post-rpc interceptor for delete_operation - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_get_operation( - self, request: operations_pb2.GetOperationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_operation - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - def pre_list_operations( - self, request: operations_pb2.ListOperationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[operations_pb2.ListOperationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_operations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Registry server. - """ - return request, metadata - - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations - - Override in a subclass to manipulate the response - after it is returned by the Registry server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class RegistryRestStub: - _session: AuthorizedSession - _host: str - _interceptor: RegistryRestInterceptor - - -class RegistryRestTransport(RegistryTransport): - """REST backend transport for Registry. - - The Registry service allows teams to manage descriptions of - APIs. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - - """ - - def __init__(self, *, - host: str = 'apigeeregistry.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - client_cert_source_for_mtls: Optional[Callable[[ - ], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - interceptor: Optional[RegistryRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or RegistryRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateApi(RegistryRestStub): - def __hash__(self): - return hash("CreateApi") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "apiId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.CreateApiRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.Api: - r"""Call the create api method over HTTP. - - Args: - request (~.registry_service.CreateApiRequest): - The request object. Request message for CreateApi. - 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: - ~.registry_models.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/apis', - 'body': 'api', - }, - ] - request, metadata = self._interceptor.pre_create_api(request, metadata) - pb_request = registry_service.CreateApiRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.Api() - pb_resp = registry_models.Api.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_api(resp) - return resp - - class _CreateApiDeployment(RegistryRestStub): - def __hash__(self): - return hash("CreateApiDeployment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "apiDeploymentId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.CreateApiDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiDeployment: - r"""Call the create api deployment method over HTTP. - - Args: - request (~.registry_service.CreateApiDeploymentRequest): - The request object. Request message for - CreateApiDeployment. - - 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: - ~.registry_models.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/deployments', - 'body': 'api_deployment', - }, - ] - request, metadata = self._interceptor.pre_create_api_deployment(request, metadata) - pb_request = registry_service.CreateApiDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiDeployment() - pb_resp = registry_models.ApiDeployment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_api_deployment(resp) - return resp - - class _CreateApiSpec(RegistryRestStub): - def __hash__(self): - return hash("CreateApiSpec") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "apiSpecId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.CreateApiSpecRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiSpec: - r"""Call the create api spec method over HTTP. - - Args: - request (~.registry_service.CreateApiSpecRequest): - The request object. Request message for CreateApiSpec. - 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: - ~.registry_models.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs', - 'body': 'api_spec', - }, - ] - request, metadata = self._interceptor.pre_create_api_spec(request, metadata) - pb_request = registry_service.CreateApiSpecRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiSpec() - pb_resp = registry_models.ApiSpec.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_api_spec(resp) - return resp - - class _CreateApiVersion(RegistryRestStub): - def __hash__(self): - return hash("CreateApiVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "apiVersionId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.CreateApiVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiVersion: - r"""Call the create api version method over HTTP. - - Args: - request (~.registry_service.CreateApiVersionRequest): - The request object. Request message for CreateApiVersion. - 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: - ~.registry_models.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/versions', - 'body': 'api_version', - }, - ] - request, metadata = self._interceptor.pre_create_api_version(request, metadata) - pb_request = registry_service.CreateApiVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiVersion() - pb_resp = registry_models.ApiVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_api_version(resp) - return resp - - class _CreateArtifact(RegistryRestStub): - def __hash__(self): - return hash("CreateArtifact") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "artifactId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.CreateArtifactRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.Artifact: - r"""Call the create artifact method over HTTP. - - Args: - request (~.registry_service.CreateArtifactRequest): - The request object. Request message for CreateArtifact. - 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: - ~.registry_models.Artifact: - Artifacts of resources. Artifacts are unique - (single-value) per resource and are used to store - metadata that is too large or numerous to be stored - directly on the resource. Since artifacts are stored - separately from parent resources, they should generally - be used for metadata that is needed infrequently, i.e., - not for display in primary views of the resource but - perhaps displayed or downloaded upon request. The - ``ListArtifacts`` method allows artifacts to be quickly - enumerated and checked for presence without downloading - their (potentially-large) contents. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/artifacts', - 'body': 'artifact', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/artifacts', - 'body': 'artifact', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/artifacts', - 'body': 'artifact', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*/specs/*}/artifacts', - 'body': 'artifact', - }, -{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/deployments/*}/artifacts', - 'body': 'artifact', - }, - ] - request, metadata = self._interceptor.pre_create_artifact(request, metadata) - pb_request = registry_service.CreateArtifactRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.Artifact() - pb_resp = registry_models.Artifact.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_artifact(resp) - return resp - - class _DeleteApi(RegistryRestStub): - def __hash__(self): - return hash("DeleteApi") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.DeleteApiRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete api method over HTTP. - - Args: - request (~.registry_service.DeleteApiRequest): - The request object. Request message for DeleteApi. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_api(request, metadata) - pb_request = registry_service.DeleteApiRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteApiDeployment(RegistryRestStub): - def __hash__(self): - return hash("DeleteApiDeployment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.DeleteApiDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete api deployment method over HTTP. - - Args: - request (~.registry_service.DeleteApiDeploymentRequest): - The request object. Request message for - DeleteApiDeployment. - - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_api_deployment(request, metadata) - pb_request = registry_service.DeleteApiDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteApiDeploymentRevision(RegistryRestStub): - def __hash__(self): - return hash("DeleteApiDeploymentRevision") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.DeleteApiDeploymentRevisionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiDeployment: - r"""Call the delete api deployment - revision method over HTTP. - - Args: - request (~.registry_service.DeleteApiDeploymentRevisionRequest): - The request object. Request message for - DeleteApiDeploymentRevision. - - 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: - ~.registry_models.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:deleteRevision', - }, - ] - request, metadata = self._interceptor.pre_delete_api_deployment_revision(request, metadata) - pb_request = registry_service.DeleteApiDeploymentRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiDeployment() - pb_resp = registry_models.ApiDeployment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_api_deployment_revision(resp) - return resp - - class _DeleteApiSpec(RegistryRestStub): - def __hash__(self): - return hash("DeleteApiSpec") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.DeleteApiSpecRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete api spec method over HTTP. - - Args: - request (~.registry_service.DeleteApiSpecRequest): - The request object. Request message for DeleteApiSpec. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_api_spec(request, metadata) - pb_request = registry_service.DeleteApiSpecRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteApiSpecRevision(RegistryRestStub): - def __hash__(self): - return hash("DeleteApiSpecRevision") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.DeleteApiSpecRevisionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiSpec: - r"""Call the delete api spec revision method over HTTP. - - Args: - request (~.registry_service.DeleteApiSpecRevisionRequest): - The request object. Request message for - DeleteApiSpecRevision. - - 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: - ~.registry_models.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:deleteRevision', - }, - ] - request, metadata = self._interceptor.pre_delete_api_spec_revision(request, metadata) - pb_request = registry_service.DeleteApiSpecRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiSpec() - pb_resp = registry_models.ApiSpec.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_api_spec_revision(resp) - return resp - - class _DeleteApiVersion(RegistryRestStub): - def __hash__(self): - return hash("DeleteApiVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.DeleteApiVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete api version method over HTTP. - - Args: - request (~.registry_service.DeleteApiVersionRequest): - The request object. Request message for DeleteApiVersion. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_api_version(request, metadata) - pb_request = registry_service.DeleteApiVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _DeleteArtifact(RegistryRestStub): - def __hash__(self): - return hash("DeleteArtifact") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.DeleteArtifactRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete artifact method over HTTP. - - Args: - request (~.registry_service.DeleteArtifactRequest): - The request object. Request message for DeleteArtifact. - 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/artifacts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/artifacts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/artifacts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}', - }, -{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_artifact(request, metadata) - pb_request = registry_service.DeleteArtifactRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - class _GetApi(RegistryRestStub): - def __hash__(self): - return hash("GetApi") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.GetApiRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.Api: - r"""Call the get api method over HTTP. - - Args: - request (~.registry_service.GetApiRequest): - The request object. Request message for GetApi. - 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: - ~.registry_models.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*}', - }, - ] - request, metadata = self._interceptor.pre_get_api(request, metadata) - pb_request = registry_service.GetApiRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.Api() - pb_resp = registry_models.Api.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_api(resp) - return resp - - class _GetApiDeployment(RegistryRestStub): - def __hash__(self): - return hash("GetApiDeployment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.GetApiDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiDeployment: - r"""Call the get api deployment method over HTTP. - - Args: - request (~.registry_service.GetApiDeploymentRequest): - The request object. Request message for GetApiDeployment. - 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: - ~.registry_models.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}', - }, - ] - request, metadata = self._interceptor.pre_get_api_deployment(request, metadata) - pb_request = registry_service.GetApiDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiDeployment() - pb_resp = registry_models.ApiDeployment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_api_deployment(resp) - return resp - - class _GetApiSpec(RegistryRestStub): - def __hash__(self): - return hash("GetApiSpec") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.GetApiSpecRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiSpec: - r"""Call the get api spec method over HTTP. - - Args: - request (~.registry_service.GetApiSpecRequest): - The request object. Request message for GetApiSpec. - 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: - ~.registry_models.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}', - }, - ] - request, metadata = self._interceptor.pre_get_api_spec(request, metadata) - pb_request = registry_service.GetApiSpecRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiSpec() - pb_resp = registry_models.ApiSpec.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_api_spec(resp) - return resp - - class _GetApiSpecContents(RegistryRestStub): - def __hash__(self): - return hash("GetApiSpecContents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.GetApiSpecContentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> httpbody_pb2.HttpBody: - r"""Call the get api spec contents method over HTTP. - - Args: - request (~.registry_service.GetApiSpecContentsRequest): - The request object. Request message for - GetApiSpecContents. - - 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: - ~.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It - should only be used for payload formats that can't be - represented as JSON, such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as the - response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request fields - and also want access to the raw HTTP body. - - Example: - - :: - - message GetResourceRequest { - // A unique request id. - string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - :: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:getContents', - }, - ] - request, metadata = self._interceptor.pre_get_api_spec_contents(request, metadata) - pb_request = registry_service.GetApiSpecContentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = httpbody_pb2.HttpBody() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_api_spec_contents(resp) - return resp - - class _GetApiVersion(RegistryRestStub): - def __hash__(self): - return hash("GetApiVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.GetApiVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiVersion: - r"""Call the get api version method over HTTP. - - Args: - request (~.registry_service.GetApiVersionRequest): - The request object. Request message for GetApiVersion. - 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: - ~.registry_models.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*}', - }, - ] - request, metadata = self._interceptor.pre_get_api_version(request, metadata) - pb_request = registry_service.GetApiVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiVersion() - pb_resp = registry_models.ApiVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_api_version(resp) - return resp - - class _GetArtifact(RegistryRestStub): - def __hash__(self): - return hash("GetArtifact") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.GetArtifactRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.Artifact: - r"""Call the get artifact method over HTTP. - - Args: - request (~.registry_service.GetArtifactRequest): - The request object. Request message for GetArtifact. - 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: - ~.registry_models.Artifact: - Artifacts of resources. Artifacts are unique - (single-value) per resource and are used to store - metadata that is too large or numerous to be stored - directly on the resource. Since artifacts are stored - separately from parent resources, they should generally - be used for metadata that is needed infrequently, i.e., - not for display in primary views of the resource but - perhaps displayed or downloaded upon request. The - ``ListArtifacts`` method allows artifacts to be quickly - enumerated and checked for presence without downloading - their (potentially-large) contents. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/artifacts/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/artifacts/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/artifacts/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}', - }, - ] - request, metadata = self._interceptor.pre_get_artifact(request, metadata) - pb_request = registry_service.GetArtifactRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.Artifact() - pb_resp = registry_models.Artifact.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_artifact(resp) - return resp - - class _GetArtifactContents(RegistryRestStub): - def __hash__(self): - return hash("GetArtifactContents") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.GetArtifactContentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> httpbody_pb2.HttpBody: - r"""Call the get artifact contents method over HTTP. - - Args: - request (~.registry_service.GetArtifactContentsRequest): - The request object. Request message for - GetArtifactContents. - - 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: - ~.httpbody_pb2.HttpBody: - Message that represents an arbitrary HTTP body. It - should only be used for payload formats that can't be - represented as JSON, such as raw binary or an HTML page. - - This message can be used both in streaming and - non-streaming API methods in the request as well as the - response. - - It can be used as a top-level request field, which is - convenient if one wants to extract parameters from - either the URL or HTTP template into the request fields - and also want access to the raw HTTP body. - - Example: - - :: - - message GetResourceRequest { - // A unique request id. - string request_id = 1; - - // The raw HTTP body is bound to this field. - google.api.HttpBody http_body = 2; - - } - - service ResourceService { - rpc GetResource(GetResourceRequest) - returns (google.api.HttpBody); - rpc UpdateResource(google.api.HttpBody) - returns (google.protobuf.Empty); - - } - - Example with streaming methods: - - :: - - service CaldavService { - rpc GetCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - rpc UpdateCalendar(stream google.api.HttpBody) - returns (stream google.api.HttpBody); - - } - - Use of this type only changes how the request and - response bodies are handled, all other features will - continue to work unchanged. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/artifacts/*}:getContents', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/artifacts/*}:getContents', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/artifacts/*}:getContents', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:getContents', - }, -{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}:getContents', - }, - ] - request, metadata = self._interceptor.pre_get_artifact_contents(request, metadata) - pb_request = registry_service.GetArtifactContentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = httpbody_pb2.HttpBody() - pb_resp = resp - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_artifact_contents(resp) - return resp - - class _ListApiDeploymentRevisions(RegistryRestStub): - def __hash__(self): - return hash("ListApiDeploymentRevisions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ListApiDeploymentRevisionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_service.ListApiDeploymentRevisionsResponse: - r"""Call the list api deployment - revisions method over HTTP. - - Args: - request (~.registry_service.ListApiDeploymentRevisionsRequest): - The request object. Request message for - ListApiDeploymentRevisions. - - 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: - ~.registry_service.ListApiDeploymentRevisionsResponse: - Response message for - ListApiDeploymentRevisionsResponse. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:listRevisions', - }, - ] - request, metadata = self._interceptor.pre_list_api_deployment_revisions(request, metadata) - pb_request = registry_service.ListApiDeploymentRevisionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_service.ListApiDeploymentRevisionsResponse() - pb_resp = registry_service.ListApiDeploymentRevisionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_api_deployment_revisions(resp) - return resp - - class _ListApiDeployments(RegistryRestStub): - def __hash__(self): - return hash("ListApiDeployments") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ListApiDeploymentsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_service.ListApiDeploymentsResponse: - r"""Call the list api deployments method over HTTP. - - Args: - request (~.registry_service.ListApiDeploymentsRequest): - The request object. Request message for - ListApiDeployments. - - 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: - ~.registry_service.ListApiDeploymentsResponse: - Response message for - ListApiDeployments. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/deployments', - }, - ] - request, metadata = self._interceptor.pre_list_api_deployments(request, metadata) - pb_request = registry_service.ListApiDeploymentsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_service.ListApiDeploymentsResponse() - pb_resp = registry_service.ListApiDeploymentsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_api_deployments(resp) - return resp - - class _ListApis(RegistryRestStub): - def __hash__(self): - return hash("ListApis") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ListApisRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_service.ListApisResponse: - r"""Call the list apis method over HTTP. - - Args: - request (~.registry_service.ListApisRequest): - The request object. Request message for ListApis. - 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: - ~.registry_service.ListApisResponse: - Response message for ListApis. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/apis', - }, - ] - request, metadata = self._interceptor.pre_list_apis(request, metadata) - pb_request = registry_service.ListApisRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_service.ListApisResponse() - pb_resp = registry_service.ListApisResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_apis(resp) - return resp - - class _ListApiSpecRevisions(RegistryRestStub): - def __hash__(self): - return hash("ListApiSpecRevisions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ListApiSpecRevisionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_service.ListApiSpecRevisionsResponse: - r"""Call the list api spec revisions method over HTTP. - - Args: - request (~.registry_service.ListApiSpecRevisionsRequest): - The request object. Request message for - ListApiSpecRevisions. - - 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: - ~.registry_service.ListApiSpecRevisionsResponse: - Response message for - ListApiSpecRevisionsResponse. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:listRevisions', - }, - ] - request, metadata = self._interceptor.pre_list_api_spec_revisions(request, metadata) - pb_request = registry_service.ListApiSpecRevisionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_service.ListApiSpecRevisionsResponse() - pb_resp = registry_service.ListApiSpecRevisionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_api_spec_revisions(resp) - return resp - - class _ListApiSpecs(RegistryRestStub): - def __hash__(self): - return hash("ListApiSpecs") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ListApiSpecsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_service.ListApiSpecsResponse: - r"""Call the list api specs method over HTTP. - - Args: - request (~.registry_service.ListApiSpecsRequest): - The request object. Request message for ListApiSpecs. - 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: - ~.registry_service.ListApiSpecsResponse: - Response message for ListApiSpecs. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs', - }, - ] - request, metadata = self._interceptor.pre_list_api_specs(request, metadata) - pb_request = registry_service.ListApiSpecsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_service.ListApiSpecsResponse() - pb_resp = registry_service.ListApiSpecsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_api_specs(resp) - return resp - - class _ListApiVersions(RegistryRestStub): - def __hash__(self): - return hash("ListApiVersions") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ListApiVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_service.ListApiVersionsResponse: - r"""Call the list api versions method over HTTP. - - Args: - request (~.registry_service.ListApiVersionsRequest): - The request object. Request message for ListApiVersions. - 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: - ~.registry_service.ListApiVersionsResponse: - Response message for ListApiVersions. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/versions', - }, - ] - request, metadata = self._interceptor.pre_list_api_versions(request, metadata) - pb_request = registry_service.ListApiVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_service.ListApiVersionsResponse() - pb_resp = registry_service.ListApiVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_api_versions(resp) - return resp - - class _ListArtifacts(RegistryRestStub): - def __hash__(self): - return hash("ListArtifacts") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ListArtifactsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_service.ListArtifactsResponse: - r"""Call the list artifacts method over HTTP. - - Args: - request (~.registry_service.ListArtifactsRequest): - The request object. Request message for ListArtifacts. - 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: - ~.registry_service.ListArtifactsResponse: - Response message for ListArtifacts. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/artifacts', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*}/artifacts', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*}/artifacts', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/versions/*/specs/*}/artifacts', - }, -{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/apis/*/deployments/*}/artifacts', - }, - ] - request, metadata = self._interceptor.pre_list_artifacts(request, metadata) - pb_request = registry_service.ListArtifactsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_service.ListArtifactsResponse() - pb_resp = registry_service.ListArtifactsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_artifacts(resp) - return resp - - class _ReplaceArtifact(RegistryRestStub): - def __hash__(self): - return hash("ReplaceArtifact") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.ReplaceArtifactRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.Artifact: - r"""Call the replace artifact method over HTTP. - - Args: - request (~.registry_service.ReplaceArtifactRequest): - The request object. Request message for ReplaceArtifact. - 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: - ~.registry_models.Artifact: - Artifacts of resources. Artifacts are unique - (single-value) per resource and are used to store - metadata that is too large or numerous to be stored - directly on the resource. Since artifacts are stored - separately from parent resources, they should generally - be used for metadata that is needed infrequently, i.e., - not for display in primary views of the resource but - perhaps displayed or downloaded upon request. The - ``ListArtifacts`` method allows artifacts to be quickly - enumerated and checked for presence without downloading - their (potentially-large) contents. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'put', - 'uri': '/v1/{artifact.name=projects/*/locations/*/artifacts/*}', - 'body': 'artifact', - }, -{ - 'method': 'put', - 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/artifacts/*}', - 'body': 'artifact', - }, -{ - 'method': 'put', - 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/versions/*/artifacts/*}', - 'body': 'artifact', - }, -{ - 'method': 'put', - 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}', - 'body': 'artifact', - }, -{ - 'method': 'put', - 'uri': '/v1/{artifact.name=projects/*/locations/*/apis/*/deployments/*/artifacts/*}', - 'body': 'artifact', - }, - ] - request, metadata = self._interceptor.pre_replace_artifact(request, metadata) - pb_request = registry_service.ReplaceArtifactRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.Artifact() - pb_resp = registry_models.Artifact.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_replace_artifact(resp) - return resp - - class _RollbackApiDeployment(RegistryRestStub): - def __hash__(self): - return hash("RollbackApiDeployment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.RollbackApiDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiDeployment: - r"""Call the rollback api deployment method over HTTP. - - Args: - request (~.registry_service.RollbackApiDeploymentRequest): - The request object. Request message for - RollbackApiDeployment. - - 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: - ~.registry_models.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:rollback', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_rollback_api_deployment(request, metadata) - pb_request = registry_service.RollbackApiDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiDeployment() - pb_resp = registry_models.ApiDeployment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_rollback_api_deployment(resp) - return resp - - class _RollbackApiSpec(RegistryRestStub): - def __hash__(self): - return hash("RollbackApiSpec") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.RollbackApiSpecRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiSpec: - r"""Call the rollback api spec method over HTTP. - - Args: - request (~.registry_service.RollbackApiSpecRequest): - The request object. Request message for RollbackApiSpec. - 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: - ~.registry_models.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:rollback', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_rollback_api_spec(request, metadata) - pb_request = registry_service.RollbackApiSpecRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiSpec() - pb_resp = registry_models.ApiSpec.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_rollback_api_spec(resp) - return resp - - class _TagApiDeploymentRevision(RegistryRestStub): - def __hash__(self): - return hash("TagApiDeploymentRevision") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.TagApiDeploymentRevisionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiDeployment: - r"""Call the tag api deployment - revision method over HTTP. - - Args: - request (~.registry_service.TagApiDeploymentRevisionRequest): - The request object. Request message for - TagApiDeploymentRevision. - - 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: - ~.registry_models.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/deployments/*}:tagRevision', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_tag_api_deployment_revision(request, metadata) - pb_request = registry_service.TagApiDeploymentRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiDeployment() - pb_resp = registry_models.ApiDeployment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_tag_api_deployment_revision(resp) - return resp - - class _TagApiSpecRevision(RegistryRestStub): - def __hash__(self): - return hash("TagApiSpecRevision") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.TagApiSpecRevisionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiSpec: - r"""Call the tag api spec revision method over HTTP. - - Args: - request (~.registry_service.TagApiSpecRevisionRequest): - The request object. Request message for - TagApiSpecRevision. - - 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: - ~.registry_models.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:tagRevision', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_tag_api_spec_revision(request, metadata) - pb_request = registry_service.TagApiSpecRevisionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiSpec() - pb_resp = registry_models.ApiSpec.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_tag_api_spec_revision(resp) - return resp - - class _UpdateApi(RegistryRestStub): - def __hash__(self): - return hash("UpdateApi") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.UpdateApiRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.Api: - r"""Call the update api method over HTTP. - - Args: - request (~.registry_service.UpdateApiRequest): - The request object. Request message for UpdateApi. - 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: - ~.registry_models.Api: - A top-level description of an API. - Produced by producers and are - commitments to provide services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{api.name=projects/*/locations/*/apis/*}', - 'body': 'api', - }, - ] - request, metadata = self._interceptor.pre_update_api(request, metadata) - pb_request = registry_service.UpdateApiRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.Api() - pb_resp = registry_models.Api.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_api(resp) - return resp - - class _UpdateApiDeployment(RegistryRestStub): - def __hash__(self): - return hash("UpdateApiDeployment") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.UpdateApiDeploymentRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiDeployment: - r"""Call the update api deployment method over HTTP. - - Args: - request (~.registry_service.UpdateApiDeploymentRequest): - The request object. Request message for - UpdateApiDeployment. - - 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: - ~.registry_models.ApiDeployment: - Describes a service running at - particular address that provides a - particular version of an API. - ApiDeployments have revisions which - correspond to different configurations - of a single deployment in time. Revision - identifiers should be updated whenever - the served API spec or endpoint address - changes. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{api_deployment.name=projects/*/locations/*/apis/*/deployments/*}', - 'body': 'api_deployment', - }, - ] - request, metadata = self._interceptor.pre_update_api_deployment(request, metadata) - pb_request = registry_service.UpdateApiDeploymentRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiDeployment() - pb_resp = registry_models.ApiDeployment.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_api_deployment(resp) - return resp - - class _UpdateApiSpec(RegistryRestStub): - def __hash__(self): - return hash("UpdateApiSpec") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.UpdateApiSpecRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiSpec: - r"""Call the update api spec method over HTTP. - - Args: - request (~.registry_service.UpdateApiSpecRequest): - The request object. Request message for UpdateApiSpec. - 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: - ~.registry_models.ApiSpec: - Describes a version of an API in a - structured way. ApiSpecs provide formal - descriptions that consumers can use to - use a version. ApiSpec resources are - intended to be fully-resolved - descriptions of an ApiVersion. When - specs consist of multiple files, these - should be bundled together (e.g., in a - zip archive) and stored as a unit. - Multiple specs can exist to provide - representations in different API - description formats. Synchronization of - these representations would be provided - by tooling and background services. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{api_spec.name=projects/*/locations/*/apis/*/versions/*/specs/*}', - 'body': 'api_spec', - }, - ] - request, metadata = self._interceptor.pre_update_api_spec(request, metadata) - pb_request = registry_service.UpdateApiSpecRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiSpec() - pb_resp = registry_models.ApiSpec.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_api_spec(resp) - return resp - - class _UpdateApiVersion(RegistryRestStub): - def __hash__(self): - return hash("UpdateApiVersion") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - def __call__(self, - request: registry_service.UpdateApiVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> registry_models.ApiVersion: - r"""Call the update api version method over HTTP. - - Args: - request (~.registry_service.UpdateApiVersionRequest): - The request object. Request message for UpdateApiVersion. - 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: - ~.registry_models.ApiVersion: - Describes a particular version of an - API. ApiVersions are what consumers - actually use. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{api_version.name=projects/*/locations/*/apis/*/versions/*}', - 'body': 'api_version', - }, - ] - request, metadata = self._interceptor.pre_update_api_version(request, metadata) - pb_request = registry_service.UpdateApiVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - including_default_value_fields=False, - use_integers_for_enums=True - ) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - including_default_value_fields=False, - use_integers_for_enums=True, - )) - query_params.update(self._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = registry_models.ApiVersion() - pb_resp = registry_models.ApiVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_api_version(resp) - return resp - - @property - def create_api(self) -> Callable[ - [registry_service.CreateApiRequest], - registry_models.Api]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateApi(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_api_deployment(self) -> Callable[ - [registry_service.CreateApiDeploymentRequest], - registry_models.ApiDeployment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateApiDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_api_spec(self) -> Callable[ - [registry_service.CreateApiSpecRequest], - registry_models.ApiSpec]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateApiSpec(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_api_version(self) -> Callable[ - [registry_service.CreateApiVersionRequest], - registry_models.ApiVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateApiVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_artifact(self) -> Callable[ - [registry_service.CreateArtifactRequest], - registry_models.Artifact]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateArtifact(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_api(self) -> Callable[ - [registry_service.DeleteApiRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteApi(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_api_deployment(self) -> Callable[ - [registry_service.DeleteApiDeploymentRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteApiDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_api_deployment_revision(self) -> Callable[ - [registry_service.DeleteApiDeploymentRevisionRequest], - registry_models.ApiDeployment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteApiDeploymentRevision(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_api_spec(self) -> Callable[ - [registry_service.DeleteApiSpecRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteApiSpec(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_api_spec_revision(self) -> Callable[ - [registry_service.DeleteApiSpecRevisionRequest], - registry_models.ApiSpec]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteApiSpecRevision(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_api_version(self) -> Callable[ - [registry_service.DeleteApiVersionRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteApiVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_artifact(self) -> Callable[ - [registry_service.DeleteArtifactRequest], - empty_pb2.Empty]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DeleteArtifact(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_api(self) -> Callable[ - [registry_service.GetApiRequest], - registry_models.Api]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetApi(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_api_deployment(self) -> Callable[ - [registry_service.GetApiDeploymentRequest], - registry_models.ApiDeployment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetApiDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_api_spec(self) -> Callable[ - [registry_service.GetApiSpecRequest], - registry_models.ApiSpec]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetApiSpec(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_api_spec_contents(self) -> Callable[ - [registry_service.GetApiSpecContentsRequest], - httpbody_pb2.HttpBody]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetApiSpecContents(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_api_version(self) -> Callable[ - [registry_service.GetApiVersionRequest], - registry_models.ApiVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetApiVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_artifact(self) -> Callable[ - [registry_service.GetArtifactRequest], - registry_models.Artifact]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetArtifact(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_artifact_contents(self) -> Callable[ - [registry_service.GetArtifactContentsRequest], - httpbody_pb2.HttpBody]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetArtifactContents(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_api_deployment_revisions(self) -> Callable[ - [registry_service.ListApiDeploymentRevisionsRequest], - registry_service.ListApiDeploymentRevisionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListApiDeploymentRevisions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_api_deployments(self) -> Callable[ - [registry_service.ListApiDeploymentsRequest], - registry_service.ListApiDeploymentsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListApiDeployments(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_apis(self) -> Callable[ - [registry_service.ListApisRequest], - registry_service.ListApisResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListApis(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_api_spec_revisions(self) -> Callable[ - [registry_service.ListApiSpecRevisionsRequest], - registry_service.ListApiSpecRevisionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListApiSpecRevisions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_api_specs(self) -> Callable[ - [registry_service.ListApiSpecsRequest], - registry_service.ListApiSpecsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListApiSpecs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_api_versions(self) -> Callable[ - [registry_service.ListApiVersionsRequest], - registry_service.ListApiVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListApiVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_artifacts(self) -> Callable[ - [registry_service.ListArtifactsRequest], - registry_service.ListArtifactsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListArtifacts(self._session, self._host, self._interceptor) # type: ignore - - @property - def replace_artifact(self) -> Callable[ - [registry_service.ReplaceArtifactRequest], - registry_models.Artifact]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ReplaceArtifact(self._session, self._host, self._interceptor) # type: ignore - - @property - def rollback_api_deployment(self) -> Callable[ - [registry_service.RollbackApiDeploymentRequest], - registry_models.ApiDeployment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RollbackApiDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def rollback_api_spec(self) -> Callable[ - [registry_service.RollbackApiSpecRequest], - registry_models.ApiSpec]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RollbackApiSpec(self._session, self._host, self._interceptor) # type: ignore - - @property - def tag_api_deployment_revision(self) -> Callable[ - [registry_service.TagApiDeploymentRevisionRequest], - registry_models.ApiDeployment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TagApiDeploymentRevision(self._session, self._host, self._interceptor) # type: ignore - - @property - def tag_api_spec_revision(self) -> Callable[ - [registry_service.TagApiSpecRevisionRequest], - registry_models.ApiSpec]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._TagApiSpecRevision(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_api(self) -> Callable[ - [registry_service.UpdateApiRequest], - registry_models.Api]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateApi(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_api_deployment(self) -> Callable[ - [registry_service.UpdateApiDeploymentRequest], - registry_models.ApiDeployment]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateApiDeployment(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_api_spec(self) -> Callable[ - [registry_service.UpdateApiSpecRequest], - registry_models.ApiSpec]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateApiSpec(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_api_version(self) -> Callable[ - [registry_service.UpdateApiVersionRequest], - registry_models.ApiVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateApiVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(RegistryRestStub): - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object 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: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_location(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.Location() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(RegistryRestStub): - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object 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: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - - request, metadata = self._interceptor.pre_list_locations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(RegistryRestStub): - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:getIamPolicy', - }, -{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/runtime}:getIamPolicy', - }, - ] - - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(RegistryRestStub): - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:setIamPolicy', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/runtime}:setIamPolicy', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.loads(json.dumps(transcoded_request['body'])) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = policy_pb2.Policy() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(RegistryRestStub): - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/deployments/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/apis/*/versions/*/specs/*/artifacts/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/instances/*}:testIamPermissions', - 'body': '*', - }, -{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/runtime}:testIamPermissions', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.loads(json.dumps(transcoded_request['body'])) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def cancel_operation(self): - return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore - - class _CancelOperation(RegistryRestStub): - def __call__(self, - request: operations_pb2.CancelOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the cancel operation method over HTTP. - - Args: - request (operations_pb2.CancelOperationRequest): - The request object 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}:cancel', - 'body': '*', - }, - ] - - request, metadata = self._interceptor.pre_cancel_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - body = json.loads(json.dumps(transcoded_request['body'])) - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - data=body, - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_cancel_operation(None) - - @property - def delete_operation(self): - return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore - - class _DeleteOperation(RegistryRestStub): - def __call__(self, - request: operations_pb2.DeleteOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> None: - - r"""Call the delete operation method over HTTP. - - Args: - request (operations_pb2.DeleteOperationRequest): - The request object 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. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_delete_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - return self._interceptor.post_delete_operation(None) - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(RegistryRestStub): - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - - r"""Call the get operation method over HTTP. - - Args: - request (operations_pb2.GetOperationRequest): - The request object 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: Response from GetOperation method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - - request, metadata = self._interceptor.pre_get_operation(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.Operation() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def list_operations(self): - return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore - - class _ListOperations(RegistryRestStub): - def __call__(self, - request: operations_pb2.ListOperationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.ListOperationsResponse: - - r"""Call the list operations method over HTTP. - - Args: - request (operations_pb2.ListOperationsRequest): - The request object 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 from ListOperations method. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}/operations', - }, - ] - - request, metadata = self._interceptor.pre_list_operations(request, metadata) - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - - # Jsonify the query params - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - - # Send the request - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - - response = getattr(self._session, method)( - "{host}{uri}".format(host=self._host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params), - ) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - resp = operations_pb2.ListOperationsResponse() - resp = json_format.Parse(response.content.decode("utf-8"), resp) - resp = self._interceptor.post_list_operations(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'RegistryRestTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py deleted file mode 100644 index 0471a2f..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/__init__.py +++ /dev/null @@ -1,128 +0,0 @@ -# -*- 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. -# -from .provisioning_service import ( - CreateInstanceRequest, - DeleteInstanceRequest, - GetInstanceRequest, - Instance, - OperationMetadata, -) -from .registry_models import ( - Api, - ApiDeployment, - ApiSpec, - ApiVersion, - Artifact, -) -from .registry_service import ( - CreateApiDeploymentRequest, - CreateApiRequest, - CreateApiSpecRequest, - CreateApiVersionRequest, - CreateArtifactRequest, - DeleteApiDeploymentRequest, - DeleteApiDeploymentRevisionRequest, - DeleteApiRequest, - DeleteApiSpecRequest, - DeleteApiSpecRevisionRequest, - DeleteApiVersionRequest, - DeleteArtifactRequest, - GetApiDeploymentRequest, - GetApiRequest, - GetApiSpecContentsRequest, - GetApiSpecRequest, - GetApiVersionRequest, - GetArtifactContentsRequest, - GetArtifactRequest, - ListApiDeploymentRevisionsRequest, - ListApiDeploymentRevisionsResponse, - ListApiDeploymentsRequest, - ListApiDeploymentsResponse, - ListApiSpecRevisionsRequest, - ListApiSpecRevisionsResponse, - ListApiSpecsRequest, - ListApiSpecsResponse, - ListApisRequest, - ListApisResponse, - ListApiVersionsRequest, - ListApiVersionsResponse, - ListArtifactsRequest, - ListArtifactsResponse, - ReplaceArtifactRequest, - RollbackApiDeploymentRequest, - RollbackApiSpecRequest, - TagApiDeploymentRevisionRequest, - TagApiSpecRevisionRequest, - UpdateApiDeploymentRequest, - UpdateApiRequest, - UpdateApiSpecRequest, - UpdateApiVersionRequest, -) - -__all__ = ( - 'CreateInstanceRequest', - 'DeleteInstanceRequest', - 'GetInstanceRequest', - 'Instance', - 'OperationMetadata', - 'Api', - 'ApiDeployment', - 'ApiSpec', - 'ApiVersion', - 'Artifact', - 'CreateApiDeploymentRequest', - 'CreateApiRequest', - 'CreateApiSpecRequest', - 'CreateApiVersionRequest', - 'CreateArtifactRequest', - 'DeleteApiDeploymentRequest', - 'DeleteApiDeploymentRevisionRequest', - 'DeleteApiRequest', - 'DeleteApiSpecRequest', - 'DeleteApiSpecRevisionRequest', - 'DeleteApiVersionRequest', - 'DeleteArtifactRequest', - 'GetApiDeploymentRequest', - 'GetApiRequest', - 'GetApiSpecContentsRequest', - 'GetApiSpecRequest', - 'GetApiVersionRequest', - 'GetArtifactContentsRequest', - 'GetArtifactRequest', - 'ListApiDeploymentRevisionsRequest', - 'ListApiDeploymentRevisionsResponse', - 'ListApiDeploymentsRequest', - 'ListApiDeploymentsResponse', - 'ListApiSpecRevisionsRequest', - 'ListApiSpecRevisionsResponse', - 'ListApiSpecsRequest', - 'ListApiSpecsResponse', - 'ListApisRequest', - 'ListApisResponse', - 'ListApiVersionsRequest', - 'ListApiVersionsResponse', - 'ListArtifactsRequest', - 'ListArtifactsResponse', - 'ReplaceArtifactRequest', - 'RollbackApiDeploymentRequest', - 'RollbackApiSpecRequest', - 'TagApiDeploymentRevisionRequest', - 'TagApiSpecRevisionRequest', - 'UpdateApiDeploymentRequest', - 'UpdateApiRequest', - 'UpdateApiSpecRequest', - 'UpdateApiVersionRequest', -) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py deleted file mode 100644 index 9ed2198..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/provisioning_service.py +++ /dev/null @@ -1,262 +0,0 @@ -# -*- 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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.apigeeregistry.v1', - manifest={ - 'CreateInstanceRequest', - 'DeleteInstanceRequest', - 'GetInstanceRequest', - 'OperationMetadata', - 'Instance', - }, -) - - -class CreateInstanceRequest(proto.Message): - r"""Request message for CreateInstance. - - Attributes: - parent (str): - Required. Parent resource of the Instance, of the form: - ``projects/*/locations/*`` - instance_id (str): - Required. Identifier to assign to the - Instance. Must be unique within scope of the - parent resource. - instance (google.cloud.apigee_registry_v1.types.Instance): - Required. The Instance. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - instance_id: str = proto.Field( - proto.STRING, - number=2, - ) - instance: 'Instance' = proto.Field( - proto.MESSAGE, - number=3, - message='Instance', - ) - - -class DeleteInstanceRequest(proto.Message): - r"""Request message for DeleteInstance. - - Attributes: - name (str): - Required. The name of the Instance to delete. Format: - ``projects/*/locations/*/instances/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetInstanceRequest(proto.Message): - r"""Request message for GetInstance. - - Attributes: - name (str): - Required. The name of the Instance to retrieve. Format: - ``projects/*/locations/*/instances/*``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OperationMetadata(proto.Message): - r"""Represents the metadata of the long-running operation. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation was created. - end_time (google.protobuf.timestamp_pb2.Timestamp): - The time the operation finished running. - target (str): - Server-defined resource path for the target - of the operation. - verb (str): - Name of the verb executed by the operation. - status_message (str): - Human-readable status of the operation, if - any. - cancellation_requested (bool): - Identifies whether the user has requested cancellation of - the operation. Operations that have successfully been - cancelled have [Operation.error][] value with a - [google.rpc.Status.code][google.rpc.Status.code] of 1, - corresponding to ``Code.CANCELLED``. - api_version (str): - API version used to start the operation. - """ - - create_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, - ) - target: str = proto.Field( - proto.STRING, - number=3, - ) - verb: str = proto.Field( - proto.STRING, - number=4, - ) - status_message: str = proto.Field( - proto.STRING, - number=5, - ) - cancellation_requested: bool = proto.Field( - proto.BOOL, - number=6, - ) - api_version: str = proto.Field( - proto.STRING, - number=7, - ) - - -class Instance(proto.Message): - r"""An Instance represents the instance resources of the - Registry. Currently, only one instance is allowed for each - project. - - Attributes: - name (str): - Format: ``projects/*/locations/*/instance``. Currently only - ``locations/global`` is supported. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation timestamp. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last update timestamp. - state (google.cloud.apigee_registry_v1.types.Instance.State): - Output only. The current state of the - Instance. - state_message (str): - Output only. Extra information of Instance.State if the - state is ``FAILED``. - config (google.cloud.apigee_registry_v1.types.Instance.Config): - Required. Config of the Instance. - """ - class State(proto.Enum): - r"""State of the Instance. - - Values: - STATE_UNSPECIFIED (0): - The default value. This value is used if the - state is omitted. - INACTIVE (1): - The Instance has not been initialized or has - been deleted. - CREATING (2): - The Instance is being created. - ACTIVE (3): - The Instance has been created and is ready - for use. - UPDATING (4): - The Instance is being updated. - DELETING (5): - The Instance is being deleted. - FAILED (6): - The Instance encountered an error during a - state change. - """ - STATE_UNSPECIFIED = 0 - INACTIVE = 1 - CREATING = 2 - ACTIVE = 3 - UPDATING = 4 - DELETING = 5 - FAILED = 6 - - class Config(proto.Message): - r"""Available configurations to provision an Instance. - - Attributes: - location (str): - Output only. The GCP location where the - Instance resides. - cmek_key_name (str): - Required. The Customer Managed Encryption Key (CMEK) used - for data encryption. The CMEK name should follow the format - of - ``projects/([^/]+)/locations/([^/]+)/keyRings/([^/]+)/cryptoKeys/([^/]+)``, - where the ``location`` must match InstanceConfig.location. - """ - - location: str = proto.Field( - proto.STRING, - number=1, - ) - cmek_key_name: str = proto.Field( - proto.STRING, - number=2, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - state_message: str = proto.Field( - proto.STRING, - number=5, - ) - config: Config = proto.Field( - proto.MESSAGE, - number=6, - message=Config, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py deleted file mode 100644 index 34991bd..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_models.py +++ /dev/null @@ -1,573 +0,0 @@ -# -*- 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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.apigeeregistry.v1', - manifest={ - 'Api', - 'ApiVersion', - 'ApiSpec', - 'ApiDeployment', - 'Artifact', - }, -) - - -class Api(proto.Message): - r"""A top-level description of an API. - Produced by producers and are commitments to provide services. - - Attributes: - name (str): - Resource name. - display_name (str): - Human-meaningful name. - description (str): - A detailed description. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation timestamp. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last update timestamp. - availability (str): - A user-definable description of the - availability of this service. Format: free-form, - but we expect single words that describe - availability, e.g., "NONE", "TESTING", - "PREVIEW", "GENERAL", "DEPRECATED", "SHUTDOWN". - recommended_version (str): - The recommended version of the API. Format: - ``apis/{api}/versions/{version}`` - recommended_deployment (str): - The recommended deployment of the API. Format: - ``apis/{api}/deployments/{deployment}`` - labels (MutableMapping[str, str]): - Labels attach identifying metadata to resources. Identifying - metadata can be used to filter list operations. - - Label keys and values can be no longer than 64 characters - (Unicode codepoints), can only contain lowercase letters, - numeric characters, underscores, and dashes. International - characters are allowed. No more than 64 user labels can be - associated with one resource (System labels are excluded). - - See https://goo.gl/xmQnxf for more information and examples - of labels. System reserved label keys are prefixed with - ``apigeeregistry.googleapis.com/`` and cannot be changed. - annotations (MutableMapping[str, str]): - Annotations attach non-identifying metadata - to resources. - Annotation keys and values are less restricted - than those of labels, but should be generally - used for small values of broad interest. Larger, - topic- specific metadata should be stored in - Artifacts. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - availability: str = proto.Field( - proto.STRING, - number=6, - ) - recommended_version: str = proto.Field( - proto.STRING, - number=7, - ) - recommended_deployment: str = proto.Field( - proto.STRING, - number=8, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=9, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - - -class ApiVersion(proto.Message): - r"""Describes a particular version of an API. - ApiVersions are what consumers actually use. - - Attributes: - name (str): - Resource name. - display_name (str): - Human-meaningful name. - description (str): - A detailed description. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation timestamp. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last update timestamp. - state (str): - A user-definable description of the lifecycle - phase of this API version. Format: free-form, - but we expect single words that describe API - maturity, e.g., "CONCEPT", "DESIGN", - "DEVELOPMENT", "STAGING", "PRODUCTION", - "DEPRECATED", "RETIRED". - labels (MutableMapping[str, str]): - Labels attach identifying metadata to resources. Identifying - metadata can be used to filter list operations. - - Label keys and values can be no longer than 64 characters - (Unicode codepoints), can only contain lowercase letters, - numeric characters, underscores and dashes. International - characters are allowed. No more than 64 user labels can be - associated with one resource (System labels are excluded). - - See https://goo.gl/xmQnxf for more information and examples - of labels. System reserved label keys are prefixed with - ``apigeeregistry.googleapis.com/`` and cannot be changed. - annotations (MutableMapping[str, str]): - Annotations attach non-identifying metadata - to resources. - Annotation keys and values are less restricted - than those of labels, but should be generally - used for small values of broad interest. Larger, - topic- specific metadata should be stored in - Artifacts. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - state: str = proto.Field( - proto.STRING, - number=6, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=8, - ) - - -class ApiSpec(proto.Message): - r"""Describes a version of an API in a structured way. - ApiSpecs provide formal descriptions that consumers can use to - use a version. ApiSpec resources are intended to be - fully-resolved descriptions of an ApiVersion. When specs consist - of multiple files, these should be bundled together (e.g., in a - zip archive) and stored as a unit. Multiple specs can exist to - provide representations in different API description formats. - Synchronization of these representations would be provided by - tooling and background services. - - Attributes: - name (str): - Resource name. - filename (str): - A possibly-hierarchical name used to refer to - the spec from other specs. - description (str): - A detailed description. - revision_id (str): - Output only. Immutable. The revision ID of - the spec. A new revision is committed whenever - the spec contents are changed. The format is an - 8-character hexadecimal string. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation timestamp; when the - spec resource was created. - revision_create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Revision creation timestamp; - when the represented revision was created. - revision_update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last update timestamp: when the - represented revision was last modified. - mime_type (str): - A style (format) descriptor for this spec that is specified - as a Media Type (https://en.wikipedia.org/wiki/Media_type). - Possible values include ``application/vnd.apigee.proto``, - ``application/vnd.apigee.openapi``, and - ``application/vnd.apigee.graphql``, with possible suffixes - representing compression types. These hypothetical names are - defined in the vendor tree defined in RFC6838 - (https://tools.ietf.org/html/rfc6838) and are not final. - Content types can specify compression. Currently only GZip - compression is supported (indicated with "+gzip"). - size_bytes (int): - Output only. The size of the spec file in - bytes. If the spec is gzipped, this is the size - of the uncompressed spec. - hash_ (str): - Output only. A SHA-256 hash of the spec's - contents. If the spec is gzipped, this is the - hash of the uncompressed spec. - source_uri (str): - The original source URI of the spec (if one - exists). This is an external location that can - be used for reference purposes but which may not - be authoritative since this external resource - may change after the spec is retrieved. - contents (bytes): - Input only. The contents of the spec. - Provided by API callers when specs are created - or updated. To access the contents of a spec, - use GetApiSpecContents. - labels (MutableMapping[str, str]): - Labels attach identifying metadata to resources. Identifying - metadata can be used to filter list operations. - - Label keys and values can be no longer than 64 characters - (Unicode codepoints), can only contain lowercase letters, - numeric characters, underscores and dashes. International - characters are allowed. No more than 64 user labels can be - associated with one resource (System labels are excluded). - - See https://goo.gl/xmQnxf for more information and examples - of labels. System reserved label keys are prefixed with - ``apigeeregistry.googleapis.com/`` and cannot be changed. - annotations (MutableMapping[str, str]): - Annotations attach non-identifying metadata - to resources. - Annotation keys and values are less restricted - than those of labels, but should be generally - used for small values of broad interest. Larger, - topic- specific metadata should be stored in - Artifacts. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - filename: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - revision_id: str = proto.Field( - proto.STRING, - number=4, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - revision_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - revision_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - mime_type: str = proto.Field( - proto.STRING, - number=8, - ) - size_bytes: int = proto.Field( - proto.INT32, - number=9, - ) - hash_: str = proto.Field( - proto.STRING, - number=10, - ) - source_uri: str = proto.Field( - proto.STRING, - number=11, - ) - contents: bytes = proto.Field( - proto.BYTES, - number=12, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - - -class ApiDeployment(proto.Message): - r"""Describes a service running at particular address that - provides a particular version of an API. ApiDeployments have - revisions which correspond to different configurations of a - single deployment in time. Revision identifiers should be - updated whenever the served API spec or endpoint address - changes. - - Attributes: - name (str): - Resource name. - display_name (str): - Human-meaningful name. - description (str): - A detailed description. - revision_id (str): - Output only. Immutable. The revision ID of - the deployment. A new revision is committed - whenever the deployment contents are changed. - The format is an 8-character hexadecimal string. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation timestamp; when the - deployment resource was created. - revision_create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Revision creation timestamp; - when the represented revision was created. - revision_update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last update timestamp: when the - represented revision was last modified. - api_spec_revision (str): - The full resource name (including revision ID) of the spec - of the API being served by the deployment. Changes to this - value will update the revision. Format: - ``apis/{api}/deployments/{deployment}`` - endpoint_uri (str): - The address where the deployment is serving. - Changes to this value will update the revision. - external_channel_uri (str): - The address of the external channel of the - API (e.g., the Developer Portal). Changes to - this value will not affect the revision. - intended_audience (str): - Text briefly identifying the intended - audience of the API. Changes to this value will - not affect the revision. - access_guidance (str): - Text briefly describing how to access the - endpoint. Changes to this value will not affect - the revision. - labels (MutableMapping[str, str]): - Labels attach identifying metadata to resources. Identifying - metadata can be used to filter list operations. - - Label keys and values can be no longer than 64 characters - (Unicode codepoints), can only contain lowercase letters, - numeric characters, underscores and dashes. International - characters are allowed. No more than 64 user labels can be - associated with one resource (System labels are excluded). - - See https://goo.gl/xmQnxf for more information and examples - of labels. System reserved label keys are prefixed with - ``apigeeregistry.googleapis.com/`` and cannot be changed. - annotations (MutableMapping[str, str]): - Annotations attach non-identifying metadata - to resources. - Annotation keys and values are less restricted - than those of labels, but should be generally - used for small values of broad interest. Larger, - topic- specific metadata should be stored in - Artifacts. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - display_name: str = proto.Field( - proto.STRING, - number=2, - ) - description: str = proto.Field( - proto.STRING, - number=3, - ) - revision_id: str = proto.Field( - proto.STRING, - number=4, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - revision_create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - revision_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - api_spec_revision: str = proto.Field( - proto.STRING, - number=8, - ) - endpoint_uri: str = proto.Field( - proto.STRING, - number=9, - ) - external_channel_uri: str = proto.Field( - proto.STRING, - number=10, - ) - intended_audience: str = proto.Field( - proto.STRING, - number=11, - ) - access_guidance: str = proto.Field( - proto.STRING, - number=12, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=14, - ) - annotations: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=15, - ) - - -class Artifact(proto.Message): - r"""Artifacts of resources. Artifacts are unique (single-value) per - resource and are used to store metadata that is too large or - numerous to be stored directly on the resource. Since artifacts are - stored separately from parent resources, they should generally be - used for metadata that is needed infrequently, i.e., not for display - in primary views of the resource but perhaps displayed or downloaded - upon request. The ``ListArtifacts`` method allows artifacts to be - quickly enumerated and checked for presence without downloading - their (potentially-large) contents. - - Attributes: - name (str): - Resource name. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Creation timestamp. - update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. Last update timestamp. - mime_type (str): - A content type specifier for the artifact. Content type - specifiers are Media Types - (https://en.wikipedia.org/wiki/Media_type) with a possible - "schema" parameter that specifies a schema for the stored - information. Content types can specify compression. - Currently only GZip compression is supported (indicated with - "+gzip"). - size_bytes (int): - Output only. The size of the artifact in - bytes. If the artifact is gzipped, this is the - size of the uncompressed artifact. - hash_ (str): - Output only. A SHA-256 hash of the artifact's - contents. If the artifact is gzipped, this is - the hash of the uncompressed artifact. - contents (bytes): - Input only. The contents of the artifact. - Provided by API callers when artifacts are - created or replaced. To access the contents of - an artifact, use GetArtifactContents. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - mime_type: str = proto.Field( - proto.STRING, - number=4, - ) - size_bytes: int = proto.Field( - proto.INT32, - number=5, - ) - hash_: str = proto.Field( - proto.STRING, - number=6, - ) - contents: bytes = proto.Field( - proto.BYTES, - number=7, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py b/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py deleted file mode 100644 index ea6ea04..0000000 --- a/owl-bot-staging/v1/google/cloud/apigee_registry_v1/types/registry_service.py +++ /dev/null @@ -1,1222 +0,0 @@ -# -*- 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. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.apigee_registry_v1.types import registry_models -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.apigeeregistry.v1', - manifest={ - 'ListApisRequest', - 'ListApisResponse', - 'GetApiRequest', - 'CreateApiRequest', - 'UpdateApiRequest', - 'DeleteApiRequest', - 'ListApiVersionsRequest', - 'ListApiVersionsResponse', - 'GetApiVersionRequest', - 'CreateApiVersionRequest', - 'UpdateApiVersionRequest', - 'DeleteApiVersionRequest', - 'ListApiSpecsRequest', - 'ListApiSpecsResponse', - 'GetApiSpecRequest', - 'GetApiSpecContentsRequest', - 'CreateApiSpecRequest', - 'UpdateApiSpecRequest', - 'DeleteApiSpecRequest', - 'TagApiSpecRevisionRequest', - 'ListApiSpecRevisionsRequest', - 'ListApiSpecRevisionsResponse', - 'RollbackApiSpecRequest', - 'DeleteApiSpecRevisionRequest', - 'ListApiDeploymentsRequest', - 'ListApiDeploymentsResponse', - 'GetApiDeploymentRequest', - 'CreateApiDeploymentRequest', - 'UpdateApiDeploymentRequest', - 'DeleteApiDeploymentRequest', - 'TagApiDeploymentRevisionRequest', - 'ListApiDeploymentRevisionsRequest', - 'ListApiDeploymentRevisionsResponse', - 'RollbackApiDeploymentRequest', - 'DeleteApiDeploymentRevisionRequest', - 'ListArtifactsRequest', - 'ListArtifactsResponse', - 'GetArtifactRequest', - 'GetArtifactContentsRequest', - 'CreateArtifactRequest', - 'ReplaceArtifactRequest', - 'DeleteArtifactRequest', - }, -) - - -class ListApisRequest(proto.Message): - r"""Request message for ListApis. - - Attributes: - parent (str): - Required. The parent, which owns this collection of APIs. - Format: ``projects/*/locations/*`` - page_size (int): - The maximum number of APIs to return. - The service may return fewer than this value. If - unspecified, at most 50 values will be returned. - The maximum is 1000; values above 1000 will be - coerced to 1000. - page_token (str): - A page token, received from a previous ``ListApis`` call. - Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListApis`` must match the call that provided the page - token. - filter (str): - An expression that can be used to filter the - list. Filters use the Common Expression Language - and can refer to all message fields. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListApisResponse(proto.Message): - r"""Response message for ListApis. - - Attributes: - apis (MutableSequence[google.cloud.apigee_registry_v1.types.Api]): - The APIs from the specified publisher. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - apis: MutableSequence[registry_models.Api] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=registry_models.Api, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetApiRequest(proto.Message): - r"""Request message for GetApi. - - Attributes: - name (str): - Required. The name of the API to retrieve. Format: - ``projects/*/locations/*/apis/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateApiRequest(proto.Message): - r"""Request message for CreateApi. - - Attributes: - parent (str): - Required. The parent, which owns this collection of APIs. - Format: ``projects/*/locations/*`` - api (google.cloud.apigee_registry_v1.types.Api): - Required. The API to create. - api_id (str): - Required. The ID to use for the API, which will become the - final component of the API's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - api: registry_models.Api = proto.Field( - proto.MESSAGE, - number=2, - message=registry_models.Api, - ) - api_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateApiRequest(proto.Message): - r"""Request message for UpdateApi. - - Attributes: - api (google.cloud.apigee_registry_v1.types.Api): - Required. The API to update. - - The ``name`` field is used to identify the API to update. - Format: ``projects/*/locations/*/apis/*`` - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields are - updated that are set in the request message (fields set to - default values are ignored). If an asterisk "*" is - specified, all fields are updated, including fields that are - unspecified/default in the request. - allow_missing (bool): - If set to true, and the API is not found, a new API will be - created. In this situation, ``update_mask`` is ignored. - """ - - api: registry_models.Api = proto.Field( - proto.MESSAGE, - number=1, - message=registry_models.Api, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteApiRequest(proto.Message): - r"""Request message for DeleteApi. - - Attributes: - name (str): - Required. The name of the API to delete. Format: - ``projects/*/locations/*/apis/*`` - force (bool): - If set to true, any child resources will also - be deleted. (Otherwise, the request will only - work if there are no child resources.) - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListApiVersionsRequest(proto.Message): - r"""Request message for ListApiVersions. - - Attributes: - parent (str): - Required. The parent, which owns this collection of - versions. Format: ``projects/*/locations/*/apis/*`` - page_size (int): - The maximum number of versions to return. - The service may return fewer than this value. If - unspecified, at most 50 values will be returned. - The maximum is 1000; values above 1000 will be - coerced to 1000. - page_token (str): - A page token, received from a previous ``ListApiVersions`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListApiVersions`` must match the call that provided the - page token. - filter (str): - An expression that can be used to filter the - list. Filters use the Common Expression Language - and can refer to all message fields. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListApiVersionsResponse(proto.Message): - r"""Response message for ListApiVersions. - - Attributes: - api_versions (MutableSequence[google.cloud.apigee_registry_v1.types.ApiVersion]): - The versions from the specified publisher. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - api_versions: MutableSequence[registry_models.ApiVersion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=registry_models.ApiVersion, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetApiVersionRequest(proto.Message): - r"""Request message for GetApiVersion. - - Attributes: - name (str): - Required. The name of the version to retrieve. Format: - ``projects/*/locations/*/apis/*/versions/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateApiVersionRequest(proto.Message): - r"""Request message for CreateApiVersion. - - Attributes: - parent (str): - Required. The parent, which owns this collection of - versions. Format: ``projects/*/locations/*/apis/*`` - api_version (google.cloud.apigee_registry_v1.types.ApiVersion): - Required. The version to create. - api_version_id (str): - Required. The ID to use for the version, which will become - the final component of the version's resource name. - - This value should be 1-63 characters, and valid characters - are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - api_version: registry_models.ApiVersion = proto.Field( - proto.MESSAGE, - number=2, - message=registry_models.ApiVersion, - ) - api_version_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateApiVersionRequest(proto.Message): - r"""Request message for UpdateApiVersion. - - Attributes: - api_version (google.cloud.apigee_registry_v1.types.ApiVersion): - Required. The version to update. - - The ``name`` field is used to identify the version to - update. Format: ``projects/*/locations/*/apis/*/versions/*`` - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields are - updated that are set in the request message (fields set to - default values are ignored). If an asterisk "*" is - specified, all fields are updated, including fields that are - unspecified/default in the request. - allow_missing (bool): - If set to true, and the version is not found, a new version - will be created. In this situation, ``update_mask`` is - ignored. - """ - - api_version: registry_models.ApiVersion = proto.Field( - proto.MESSAGE, - number=1, - message=registry_models.ApiVersion, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteApiVersionRequest(proto.Message): - r"""Request message for DeleteApiVersion. - - Attributes: - name (str): - Required. The name of the version to delete. Format: - ``projects/*/locations/*/apis/*/versions/*`` - force (bool): - If set to true, any child resources will also - be deleted. (Otherwise, the request will only - work if there are no child resources.) - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class ListApiSpecsRequest(proto.Message): - r"""Request message for ListApiSpecs. - - Attributes: - parent (str): - Required. The parent, which owns this collection of specs. - Format: ``projects/*/locations/*/apis/*/versions/*`` - page_size (int): - The maximum number of specs to return. - The service may return fewer than this value. If - unspecified, at most 50 values will be returned. - The maximum is 1000; values above 1000 will be - coerced to 1000. - page_token (str): - A page token, received from a previous ``ListApiSpecs`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListApiSpecs`` must match the call that provided the page - token. - filter (str): - An expression that can be used to filter the - list. Filters use the Common Expression Language - and can refer to all message fields except - contents. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListApiSpecsResponse(proto.Message): - r"""Response message for ListApiSpecs. - - Attributes: - api_specs (MutableSequence[google.cloud.apigee_registry_v1.types.ApiSpec]): - The specs from the specified publisher. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - api_specs: MutableSequence[registry_models.ApiSpec] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=registry_models.ApiSpec, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetApiSpecRequest(proto.Message): - r"""Request message for GetApiSpec. - - Attributes: - name (str): - Required. The name of the spec to retrieve. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetApiSpecContentsRequest(proto.Message): - r"""Request message for GetApiSpecContents. - - Attributes: - name (str): - Required. The name of the spec whose contents should be - retrieved. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateApiSpecRequest(proto.Message): - r"""Request message for CreateApiSpec. - - Attributes: - parent (str): - Required. The parent, which owns this collection of specs. - Format: ``projects/*/locations/*/apis/*/versions/*`` - api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): - Required. The spec to create. - api_spec_id (str): - Required. The ID to use for the spec, which will become the - final component of the spec's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - api_spec: registry_models.ApiSpec = proto.Field( - proto.MESSAGE, - number=2, - message=registry_models.ApiSpec, - ) - api_spec_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateApiSpecRequest(proto.Message): - r"""Request message for UpdateApiSpec. - - Attributes: - api_spec (google.cloud.apigee_registry_v1.types.ApiSpec): - Required. The spec to update. - - The ``name`` field is used to identify the spec to update. - Format: ``projects/*/locations/*/apis/*/versions/*/specs/*`` - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields are - updated that are set in the request message (fields set to - default values are ignored). If an asterisk "*" is - specified, all fields are updated, including fields that are - unspecified/default in the request. - allow_missing (bool): - If set to true, and the spec is not found, a new spec will - be created. In this situation, ``update_mask`` is ignored. - """ - - api_spec: registry_models.ApiSpec = proto.Field( - proto.MESSAGE, - number=1, - message=registry_models.ApiSpec, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteApiSpecRequest(proto.Message): - r"""Request message for DeleteApiSpec. - - Attributes: - name (str): - Required. The name of the spec to delete. Format: - ``projects/*/locations/*/apis/*/versions/*/specs/*`` - force (bool): - If set to true, any child resources will also - be deleted. (Otherwise, the request will only - work if there are no child resources.) - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class TagApiSpecRevisionRequest(proto.Message): - r"""Request message for TagApiSpecRevision. - - Attributes: - name (str): - Required. The name of the spec to be tagged, - including the revision ID. - tag (str): - Required. The tag to apply. The tag should be at most 40 - characters, and match ``[a-z][a-z0-9-]{3,39}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - tag: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListApiSpecRevisionsRequest(proto.Message): - r"""Request message for ListApiSpecRevisions. - - Attributes: - name (str): - Required. The name of the spec to list - revisions for. - page_size (int): - The maximum number of revisions to return per - page. - page_token (str): - The page token, received from a previous - ListApiSpecRevisions call. Provide this to - retrieve the subsequent page. - """ - - name: 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, - ) - - -class ListApiSpecRevisionsResponse(proto.Message): - r"""Response message for ListApiSpecRevisionsResponse. - - Attributes: - api_specs (MutableSequence[google.cloud.apigee_registry_v1.types.ApiSpec]): - The revisions of the spec. - next_page_token (str): - A token that can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - api_specs: MutableSequence[registry_models.ApiSpec] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=registry_models.ApiSpec, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class RollbackApiSpecRequest(proto.Message): - r"""Request message for RollbackApiSpec. - - Attributes: - name (str): - Required. The spec being rolled back. - revision_id (str): - Required. The revision ID to roll back to. It must be a - revision of the same spec. - - Example: ``c7cfa2a8`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteApiSpecRevisionRequest(proto.Message): - r"""Request message for DeleteApiSpecRevision. - - Attributes: - name (str): - Required. The name of the spec revision to be deleted, with - a revision ID explicitly included. - - Example: - ``projects/sample/locations/global/apis/petstore/versions/1.0.0/specs/openapi.yaml@c7cfa2a8`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListApiDeploymentsRequest(proto.Message): - r"""Request message for ListApiDeployments. - - Attributes: - parent (str): - Required. The parent, which owns this collection of - deployments. Format: ``projects/*/locations/*/apis/*`` - page_size (int): - The maximum number of deployments to return. - The service may return fewer than this value. If - unspecified, at most 50 values will be returned. - The maximum is 1000; values above 1000 will be - coerced to 1000. - page_token (str): - A page token, received from a previous - ``ListApiDeployments`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListApiDeployments`` must match the call that provided the - page token. - filter (str): - An expression that can be used to filter the - list. Filters use the Common Expression Language - and can refer to all message fields. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListApiDeploymentsResponse(proto.Message): - r"""Response message for ListApiDeployments. - - Attributes: - api_deployments (MutableSequence[google.cloud.apigee_registry_v1.types.ApiDeployment]): - The deployments from the specified publisher. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - api_deployments: MutableSequence[registry_models.ApiDeployment] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=registry_models.ApiDeployment, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetApiDeploymentRequest(proto.Message): - r"""Request message for GetApiDeployment. - - Attributes: - name (str): - Required. The name of the deployment to retrieve. Format: - ``projects/*/locations/*/apis/*/deployments/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateApiDeploymentRequest(proto.Message): - r"""Request message for CreateApiDeployment. - - Attributes: - parent (str): - Required. The parent, which owns this collection of - deployments. Format: ``projects/*/locations/*/apis/*`` - api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): - Required. The deployment to create. - api_deployment_id (str): - Required. The ID to use for the deployment, which will - become the final component of the deployment's resource - name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - api_deployment: registry_models.ApiDeployment = proto.Field( - proto.MESSAGE, - number=2, - message=registry_models.ApiDeployment, - ) - api_deployment_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class UpdateApiDeploymentRequest(proto.Message): - r"""Request message for UpdateApiDeployment. - - Attributes: - api_deployment (google.cloud.apigee_registry_v1.types.ApiDeployment): - Required. The deployment to update. - - The ``name`` field is used to identify the deployment to - update. Format: - ``projects/*/locations/*/apis/*/deployments/*`` - update_mask (google.protobuf.field_mask_pb2.FieldMask): - The list of fields to be updated. If omitted, all fields are - updated that are set in the request message (fields set to - default values are ignored). If an asterisk "*" is - specified, all fields are updated, including fields that are - unspecified/default in the request. - allow_missing (bool): - If set to true, and the deployment is not found, a new - deployment will be created. In this situation, - ``update_mask`` is ignored. - """ - - api_deployment: registry_models.ApiDeployment = proto.Field( - proto.MESSAGE, - number=1, - message=registry_models.ApiDeployment, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - allow_missing: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class DeleteApiDeploymentRequest(proto.Message): - r"""Request message for DeleteApiDeployment. - - Attributes: - name (str): - Required. The name of the deployment to delete. Format: - ``projects/*/locations/*/apis/*/deployments/*`` - force (bool): - If set to true, any child resources will also - be deleted. (Otherwise, the request will only - work if there are no child resources.) - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - force: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -class TagApiDeploymentRevisionRequest(proto.Message): - r"""Request message for TagApiDeploymentRevision. - - Attributes: - name (str): - Required. The name of the deployment to be - tagged, including the revision ID. - tag (str): - Required. The tag to apply. The tag should be at most 40 - characters, and match ``[a-z][a-z0-9-]{3,39}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - tag: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ListApiDeploymentRevisionsRequest(proto.Message): - r"""Request message for ListApiDeploymentRevisions. - - Attributes: - name (str): - Required. The name of the deployment to list - revisions for. - page_size (int): - The maximum number of revisions to return per - page. - page_token (str): - The page token, received from a previous - ListApiDeploymentRevisions call. Provide this to - retrieve the subsequent page. - """ - - name: 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, - ) - - -class ListApiDeploymentRevisionsResponse(proto.Message): - r"""Response message for ListApiDeploymentRevisionsResponse. - - Attributes: - api_deployments (MutableSequence[google.cloud.apigee_registry_v1.types.ApiDeployment]): - The revisions of the deployment. - next_page_token (str): - A token that can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - api_deployments: MutableSequence[registry_models.ApiDeployment] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=registry_models.ApiDeployment, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class RollbackApiDeploymentRequest(proto.Message): - r"""Request message for RollbackApiDeployment. - - Attributes: - name (str): - Required. The deployment being rolled back. - revision_id (str): - Required. The revision ID to roll back to. It must be a - revision of the same deployment. - - Example: ``c7cfa2a8`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - revision_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DeleteApiDeploymentRevisionRequest(proto.Message): - r"""Request message for DeleteApiDeploymentRevision. - - Attributes: - name (str): - Required. The name of the deployment revision to be deleted, - with a revision ID explicitly included. - - Example: - ``projects/sample/locations/global/apis/petstore/deployments/prod@c7cfa2a8`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListArtifactsRequest(proto.Message): - r"""Request message for ListArtifacts. - - Attributes: - parent (str): - Required. The parent, which owns this collection of - artifacts. Format: ``{parent}`` - page_size (int): - The maximum number of artifacts to return. - The service may return fewer than this value. If - unspecified, at most 50 values will be returned. - The maximum is 1000; values above 1000 will be - coerced to 1000. - page_token (str): - A page token, received from a previous ``ListArtifacts`` - call. Provide this to retrieve the subsequent page. - - When paginating, all other parameters provided to - ``ListArtifacts`` must match the call that provided the page - token. - filter (str): - An expression that can be used to filter the - list. Filters use the Common Expression Language - and can refer to all message fields except - contents. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListArtifactsResponse(proto.Message): - r"""Response message for ListArtifacts. - - Attributes: - artifacts (MutableSequence[google.cloud.apigee_registry_v1.types.Artifact]): - The artifacts from the specified publisher. - next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. - """ - - @property - def raw_page(self): - return self - - artifacts: MutableSequence[registry_models.Artifact] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=registry_models.Artifact, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class GetArtifactRequest(proto.Message): - r"""Request message for GetArtifact. - - Attributes: - name (str): - Required. The name of the artifact to retrieve. Format: - ``{parent}/artifacts/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetArtifactContentsRequest(proto.Message): - r"""Request message for GetArtifactContents. - - Attributes: - name (str): - Required. The name of the artifact whose contents should be - retrieved. Format: ``{parent}/artifacts/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateArtifactRequest(proto.Message): - r"""Request message for CreateArtifact. - - Attributes: - parent (str): - Required. The parent, which owns this collection of - artifacts. Format: ``{parent}`` - artifact (google.cloud.apigee_registry_v1.types.Artifact): - Required. The artifact to create. - artifact_id (str): - Required. The ID to use for the artifact, which will become - the final component of the artifact's resource name. - - This value should be 4-63 characters, and valid characters - are /[a-z][0-9]-/. - - Following AIP-162, IDs must not have the form of a UUID. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - artifact: registry_models.Artifact = proto.Field( - proto.MESSAGE, - number=2, - message=registry_models.Artifact, - ) - artifact_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ReplaceArtifactRequest(proto.Message): - r"""Request message for ReplaceArtifact. - - Attributes: - artifact (google.cloud.apigee_registry_v1.types.Artifact): - Required. The artifact to replace. - - The ``name`` field is used to identify the artifact to - replace. Format: ``{parent}/artifacts/*`` - """ - - artifact: registry_models.Artifact = proto.Field( - proto.MESSAGE, - number=1, - message=registry_models.Artifact, - ) - - -class DeleteArtifactRequest(proto.Message): - r"""Request message for DeleteArtifact. - - Attributes: - name (str): - Required. The name of the artifact to delete. Format: - ``{parent}/artifacts/*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/mypy.ini b/owl-bot-staging/v1/mypy.ini deleted file mode 100644 index 574c5ae..0000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 6854282..0000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- 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. -# -import os -import pathlib -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = subprocess.check_output([sys.executable, "setup.py", "--name"], encoding="utf-8") - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.11" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "lint_setup_py", -] - -@nox.session(python=ALL_PYTHON) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/apigee_registry_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '--explicit-package-bases', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==4.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint_setup_py(session): - """Verify that setup.py is valid (including RST check).""" - session.install("docutils", "pygments") - session.run("python", "setup.py", "check", "--restructuredtext", "--strict") diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py deleted file mode 100644 index f6d04a0..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_async.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- 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 CreateInstance -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Provisioning_CreateInstance_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 apigee_registry_v1 - - -async def sample_create_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningAsyncClient() - - # Initialize request argument(s) - instance = apigee_registry_v1.Instance() - instance.config.cmek_key_name = "cmek_key_name_value" - - request = apigee_registry_v1.CreateInstanceRequest( - parent="parent_value", - instance_id="instance_id_value", - instance=instance, - ) - - # Make the request - operation = client.create_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Provisioning_CreateInstance_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py deleted file mode 100644 index 7d7c20a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_create_instance_sync.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- 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 CreateInstance -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Provisioning_CreateInstance_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 apigee_registry_v1 - - -def sample_create_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningClient() - - # Initialize request argument(s) - instance = apigee_registry_v1.Instance() - instance.config.cmek_key_name = "cmek_key_name_value" - - request = apigee_registry_v1.CreateInstanceRequest( - parent="parent_value", - instance_id="instance_id_value", - instance=instance, - ) - - # Make the request - operation = client.create_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Provisioning_CreateInstance_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py deleted file mode 100644 index a038007..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_async.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteInstance -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Provisioning_DeleteInstance_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 apigee_registry_v1 - - -async def sample_delete_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_instance(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Provisioning_DeleteInstance_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py deleted file mode 100644 index dca1a25..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_delete_instance_sync.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- 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 DeleteInstance -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Provisioning_DeleteInstance_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 apigee_registry_v1 - - -def sample_delete_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteInstanceRequest( - name="name_value", - ) - - # Make the request - operation = client.delete_instance(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Provisioning_DeleteInstance_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_async.py deleted file mode 100644 index 52aaa6a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetInstance -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Provisioning_GetInstance_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 apigee_registry_v1 - - -async def sample_get_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetInstanceRequest( - name="name_value", - ) - - # Make the request - response = await client.get_instance(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Provisioning_GetInstance_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_sync.py deleted file mode 100644 index cdd1e6c..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_provisioning_get_instance_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetInstance -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Provisioning_GetInstance_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 apigee_registry_v1 - - -def sample_get_instance(): - # Create a client - client = apigee_registry_v1.ProvisioningClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetInstanceRequest( - name="name_value", - ) - - # Make the request - response = client.get_instance(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Provisioning_GetInstance_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py deleted file mode 100644 index 1a5f46c..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApi_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 apigee_registry_v1 - - -async def sample_create_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiRequest( - parent="parent_value", - api_id="api_id_value", - ) - - # Make the request - response = await client.create_api(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py deleted file mode 100644 index a03348a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApiDeployment_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 apigee_registry_v1 - - -async def sample_create_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiDeploymentRequest( - parent="parent_value", - api_deployment_id="api_deployment_id_value", - ) - - # Make the request - response = await client.create_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py deleted file mode 100644 index 7bd457b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_deployment_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApiDeployment_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 apigee_registry_v1 - - -def sample_create_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiDeploymentRequest( - parent="parent_value", - api_deployment_id="api_deployment_id_value", - ) - - # Make the request - response = client.create_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py deleted file mode 100644 index c039d50..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApiSpec_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 apigee_registry_v1 - - -async def sample_create_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiSpecRequest( - parent="parent_value", - api_spec_id="api_spec_id_value", - ) - - # Make the request - response = await client.create_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py deleted file mode 100644 index 584e58d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_spec_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApiSpec_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 apigee_registry_v1 - - -def sample_create_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiSpecRequest( - parent="parent_value", - api_spec_id="api_spec_id_value", - ) - - # Make the request - response = client.create_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py deleted file mode 100644 index 9f243bc..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApi_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 apigee_registry_v1 - - -def sample_create_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiRequest( - parent="parent_value", - api_id="api_id_value", - ) - - # Make the request - response = client.create_api(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py deleted file mode 100644 index 8a98de3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApiVersion_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 apigee_registry_v1 - - -async def sample_create_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiVersionRequest( - parent="parent_value", - api_version_id="api_version_id_value", - ) - - # Make the request - response = await client.create_api_version(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py deleted file mode 100644 index 9c848b7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_api_version_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateApiVersion_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 apigee_registry_v1 - - -def sample_create_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateApiVersionRequest( - parent="parent_value", - api_version_id="api_version_id_value", - ) - - # Make the request - response = client.create_api_version(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py deleted file mode 100644 index 508dc04..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateArtifact_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 apigee_registry_v1 - - -async def sample_create_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateArtifactRequest( - parent="parent_value", - artifact_id="artifact_id_value", - ) - - # Make the request - response = await client.create_artifact(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py deleted file mode 100644 index 296e18d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_create_artifact_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 CreateArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_CreateArtifact_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 apigee_registry_v1 - - -def sample_create_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.CreateArtifactRequest( - parent="parent_value", - artifact_id="artifact_id_value", - ) - - # Make the request - response = client.create_artifact(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_CreateArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py deleted file mode 100644 index 9409fc9..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApi_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 apigee_registry_v1 - - -async def sample_delete_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiRequest( - name="name_value", - ) - - # Make the request - await client.delete_api(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py deleted file mode 100644 index 63ccb36..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiDeployment_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 apigee_registry_v1 - - -async def sample_delete_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRequest( - name="name_value", - ) - - # Make the request - await client.delete_api_deployment(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py deleted file mode 100644 index 1b2c107..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 DeleteApiDeploymentRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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 apigee_registry_v1 - - -async def sample_delete_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.delete_api_deployment_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py deleted file mode 100644 index e7604a8..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 DeleteApiDeploymentRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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 apigee_registry_v1 - - -def sample_delete_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.delete_api_deployment_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py deleted file mode 100644 index fc04fc0..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiDeployment_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 apigee_registry_v1 - - -def sample_delete_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiDeploymentRequest( - name="name_value", - ) - - # Make the request - client.delete_api_deployment(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py deleted file mode 100644 index 3843e1d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiSpec_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 apigee_registry_v1 - - -async def sample_delete_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRequest( - name="name_value", - ) - - # Make the request - await client.delete_api_spec(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py deleted file mode 100644 index 630027f..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 DeleteApiSpecRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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 apigee_registry_v1 - - -async def sample_delete_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRevisionRequest( - name="name_value", - ) - - # Make the request - response = await client.delete_api_spec_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py deleted file mode 100644 index 4b80ae8..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 DeleteApiSpecRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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 apigee_registry_v1 - - -def sample_delete_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRevisionRequest( - name="name_value", - ) - - # Make the request - response = client.delete_api_spec_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py deleted file mode 100644 index 4e42cdf..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_spec_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiSpec_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 apigee_registry_v1 - - -def sample_delete_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiSpecRequest( - name="name_value", - ) - - # Make the request - client.delete_api_spec(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py deleted file mode 100644 index 69f6f7c..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApi_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 apigee_registry_v1 - - -def sample_delete_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiRequest( - name="name_value", - ) - - # Make the request - client.delete_api(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py deleted file mode 100644 index 3365285..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiVersion_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 apigee_registry_v1 - - -async def sample_delete_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiVersionRequest( - name="name_value", - ) - - # Make the request - await client.delete_api_version(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py deleted file mode 100644 index de4d888..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_api_version_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteApiVersion_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 apigee_registry_v1 - - -def sample_delete_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteApiVersionRequest( - name="name_value", - ) - - # Make the request - client.delete_api_version(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py deleted file mode 100644 index 969bac2..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteArtifact_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 apigee_registry_v1 - - -async def sample_delete_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteArtifactRequest( - name="name_value", - ) - - # Make the request - await client.delete_artifact(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py deleted file mode 100644 index 69a30e8..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_delete_artifact_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- 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 DeleteArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_DeleteArtifact_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 apigee_registry_v1 - - -def sample_delete_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.DeleteArtifactRequest( - name="name_value", - ) - - # Make the request - client.delete_artifact(request=request) - - -# [END apigeeregistry_v1_generated_Registry_DeleteArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_async.py deleted file mode 100644 index a540000..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApi_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 apigee_registry_v1 - - -async def sample_get_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_async.py deleted file mode 100644 index 86643b1..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiDeployment_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 apigee_registry_v1 - - -async def sample_get_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiDeploymentRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_sync.py deleted file mode 100644 index 35577ae..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_deployment_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiDeployment_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 apigee_registry_v1 - - -def sample_get_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiDeploymentRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_async.py deleted file mode 100644 index 07e3d84..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiSpec_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 apigee_registry_v1 - - -async def sample_get_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py deleted file mode 100644 index ef4f3e4..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiSpecContents -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiSpecContents_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 apigee_registry_v1 - - -async def sample_get_api_spec_contents(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecContentsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_spec_contents(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiSpecContents_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py deleted file mode 100644 index da917ef..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiSpecContents -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiSpecContents_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 apigee_registry_v1 - - -def sample_get_api_spec_contents(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecContentsRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_spec_contents(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiSpecContents_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_sync.py deleted file mode 100644 index 0cb8879..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_spec_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiSpec_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 apigee_registry_v1 - - -def sample_get_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiSpecRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_sync.py deleted file mode 100644 index 8257a52..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApi_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 apigee_registry_v1 - - -def sample_get_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiRequest( - name="name_value", - ) - - # Make the request - response = client.get_api(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_async.py deleted file mode 100644 index 2452e5e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiVersion_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 apigee_registry_v1 - - -async def sample_get_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_api_version(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_sync.py deleted file mode 100644 index 780eba2..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_api_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetApiVersion_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 apigee_registry_v1 - - -def sample_get_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetApiVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_api_version(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_async.py deleted file mode 100644 index c8c7f51..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetArtifact_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 apigee_registry_v1 - - -async def sample_get_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactRequest( - name="name_value", - ) - - # Make the request - response = await client.get_artifact(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_async.py deleted file mode 100644 index c0a612e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetArtifactContents -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetArtifactContents_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 apigee_registry_v1 - - -async def sample_get_artifact_contents(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactContentsRequest( - name="name_value", - ) - - # Make the request - response = await client.get_artifact_contents(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetArtifactContents_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py deleted file mode 100644 index 1f76c6b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetArtifactContents -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetArtifactContents_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 apigee_registry_v1 - - -def sample_get_artifact_contents(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactContentsRequest( - name="name_value", - ) - - # Make the request - response = client.get_artifact_contents(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetArtifactContents_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_sync.py deleted file mode 100644 index 5715ea5..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_get_artifact_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- 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 GetArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_GetArtifact_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 apigee_registry_v1 - - -def sample_get_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.GetArtifactRequest( - name="name_value", - ) - - # Make the request - response = client.get_artifact(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_GetArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py deleted file mode 100644 index 3ae35f4..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiDeploymentRevisions -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_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 apigee_registry_v1 - - -async def sample_list_api_deployment_revisions(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_deployment_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py deleted file mode 100644 index 0287d20..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiDeploymentRevisions -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_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 apigee_registry_v1 - - -def sample_list_api_deployment_revisions(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_deployment_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py deleted file mode 100644 index 30a018c..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiDeployments -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiDeployments_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 apigee_registry_v1 - - -async def sample_list_api_deployments(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_deployments(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiDeployments_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py deleted file mode 100644 index e3ea45d..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_deployments_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiDeployments -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiDeployments_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 apigee_registry_v1 - - -def sample_list_api_deployments(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiDeploymentsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_deployments(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiDeployments_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py deleted file mode 100644 index addf14b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiSpecRevisions -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_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 apigee_registry_v1 - - -async def sample_list_api_spec_revisions(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_spec_revisions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py deleted file mode 100644 index aca22d7..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiSpecRevisions -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_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 apigee_registry_v1 - - -def sample_list_api_spec_revisions(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecRevisionsRequest( - name="name_value", - ) - - # Make the request - page_result = client.list_api_spec_revisions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py deleted file mode 100644 index d6dc72b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiSpecs -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiSpecs_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 apigee_registry_v1 - - -async def sample_list_api_specs(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_specs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiSpecs_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py deleted file mode 100644 index c1d948e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_specs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiSpecs -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiSpecs_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 apigee_registry_v1 - - -def sample_list_api_specs(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiSpecsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_specs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiSpecs_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py deleted file mode 100644 index 0ba03f3..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiVersions -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiVersions_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 apigee_registry_v1 - - -async def sample_list_api_versions(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiVersions_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py deleted file mode 100644 index 915b612..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_api_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApiVersions -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApiVersions_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 apigee_registry_v1 - - -def sample_list_api_versions(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApiVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_api_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApiVersions_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py deleted file mode 100644 index 2952b92..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApis -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApis_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 apigee_registry_v1 - - -async def sample_list_apis(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApisRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_apis(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApis_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py deleted file mode 100644 index 4d8502c..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_apis_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListApis -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListApis_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 apigee_registry_v1 - - -def sample_list_apis(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListApisRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_apis(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListApis_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py deleted file mode 100644 index 798682c..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListArtifacts -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListArtifacts_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 apigee_registry_v1 - - -async def sample_list_artifacts(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListArtifactsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_artifacts(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListArtifacts_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py deleted file mode 100644 index ba38cd1..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_list_artifacts_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 ListArtifacts -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ListArtifacts_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 apigee_registry_v1 - - -def sample_list_artifacts(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ListArtifactsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_artifacts(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END apigeeregistry_v1_generated_Registry_ListArtifacts_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py deleted file mode 100644 index 068f245..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 ReplaceArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ReplaceArtifact_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 apigee_registry_v1 - - -async def sample_replace_artifact(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ReplaceArtifactRequest( - ) - - # Make the request - response = await client.replace_artifact(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_ReplaceArtifact_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py deleted file mode 100644 index 3a1210b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_replace_artifact_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 ReplaceArtifact -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_ReplaceArtifact_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 apigee_registry_v1 - - -def sample_replace_artifact(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.ReplaceArtifactRequest( - ) - - # Make the request - response = client.replace_artifact(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_ReplaceArtifact_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py deleted file mode 100644 index a8b26ca..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 RollbackApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_RollbackApiDeployment_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 apigee_registry_v1 - - -async def sample_rollback_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiDeploymentRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = await client.rollback_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_RollbackApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py deleted file mode 100644 index 510524b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 RollbackApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_RollbackApiDeployment_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 apigee_registry_v1 - - -def sample_rollback_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiDeploymentRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = client.rollback_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_RollbackApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py deleted file mode 100644 index db76ddc..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 RollbackApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_RollbackApiSpec_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 apigee_registry_v1 - - -async def sample_rollback_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiSpecRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = await client.rollback_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_RollbackApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py deleted file mode 100644 index 836f10b..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 RollbackApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_RollbackApiSpec_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 apigee_registry_v1 - - -def sample_rollback_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.RollbackApiSpecRequest( - name="name_value", - revision_id="revision_id_value", - ) - - # Make the request - response = client.rollback_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_RollbackApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py deleted file mode 100644 index 7ac740a..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 TagApiDeploymentRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_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 apigee_registry_v1 - - -async def sample_tag_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiDeploymentRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = await client.tag_api_deployment_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py deleted file mode 100644 index 315be45..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 TagApiDeploymentRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_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 apigee_registry_v1 - - -def sample_tag_api_deployment_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiDeploymentRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = client.tag_api_deployment_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py deleted file mode 100644 index b97e8a6..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 TagApiSpecRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_TagApiSpecRevision_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 apigee_registry_v1 - - -async def sample_tag_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiSpecRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = await client.tag_api_spec_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_TagApiSpecRevision_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py deleted file mode 100644 index d5ddbfb..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- 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 TagApiSpecRevision -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_TagApiSpecRevision_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 apigee_registry_v1 - - -def sample_tag_api_spec_revision(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.TagApiSpecRevisionRequest( - name="name_value", - tag="tag_value", - ) - - # Make the request - response = client.tag_api_spec_revision(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_TagApiSpecRevision_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py deleted file mode 100644 index 7f0185c..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApi_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 apigee_registry_v1 - - -async def sample_update_api(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiRequest( - ) - - # Make the request - response = await client.update_api(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApi_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py deleted file mode 100644 index 34fd971..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApiDeployment_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 apigee_registry_v1 - - -async def sample_update_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiDeploymentRequest( - ) - - # Make the request - response = await client.update_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApiDeployment_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py deleted file mode 100644 index 144d745..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_deployment_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApiDeployment -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApiDeployment_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 apigee_registry_v1 - - -def sample_update_api_deployment(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiDeploymentRequest( - ) - - # Make the request - response = client.update_api_deployment(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApiDeployment_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py deleted file mode 100644 index 03059fa..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApiSpec_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 apigee_registry_v1 - - -async def sample_update_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiSpecRequest( - ) - - # Make the request - response = await client.update_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApiSpec_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py deleted file mode 100644 index 013de05..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_spec_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApiSpec -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApiSpec_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 apigee_registry_v1 - - -def sample_update_api_spec(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiSpecRequest( - ) - - # Make the request - response = client.update_api_spec(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApiSpec_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py deleted file mode 100644 index 1991426..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApi -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApi_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 apigee_registry_v1 - - -def sample_update_api(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiRequest( - ) - - # Make the request - response = client.update_api(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApi_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py deleted file mode 100644 index e275a66..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApiVersion_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 apigee_registry_v1 - - -async def sample_update_api_version(): - # Create a client - client = apigee_registry_v1.RegistryAsyncClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiVersionRequest( - ) - - # Make the request - response = await client.update_api_version(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApiVersion_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py b/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py deleted file mode 100644 index af01cc8..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/apigeeregistry_v1_generated_registry_update_api_version_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- 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 UpdateApiVersion -# 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-apigee-registry - - -# [START apigeeregistry_v1_generated_Registry_UpdateApiVersion_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 apigee_registry_v1 - - -def sample_update_api_version(): - # Create a client - client = apigee_registry_v1.RegistryClient() - - # Initialize request argument(s) - request = apigee_registry_v1.UpdateApiVersionRequest( - ) - - # Make the request - response = client.update_api_version(request=request) - - # Handle the response - print(response) - -# [END apigeeregistry_v1_generated_Registry_UpdateApiVersion_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json deleted file mode 100644 index 399743e..0000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.apigeeregistry.v1.json +++ /dev/null @@ -1,6183 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.apigeeregistry.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-apigee-registry", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient", - "shortName": "ProvisioningAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient.create_instance", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning.CreateInstance", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning", - "shortName": "Provisioning" - }, - "shortName": "CreateInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateInstanceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "instance", - "type": "google.cloud.apigee_registry_v1.types.Instance" - }, - { - "name": "instance_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_instance" - }, - "description": "Sample for CreateInstance", - "file": "apigeeregistry_v1_generated_provisioning_create_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Provisioning_CreateInstance_async", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_provisioning_create_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient", - "shortName": "ProvisioningClient" - }, - "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient.create_instance", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning.CreateInstance", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning", - "shortName": "Provisioning" - }, - "shortName": "CreateInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateInstanceRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "instance", - "type": "google.cloud.apigee_registry_v1.types.Instance" - }, - { - "name": "instance_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_instance" - }, - "description": "Sample for CreateInstance", - "file": "apigeeregistry_v1_generated_provisioning_create_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Provisioning_CreateInstance_sync", - "segments": [ - { - "end": 60, - "start": 27, - "type": "FULL" - }, - { - "end": 60, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 57, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 61, - "start": 58, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_provisioning_create_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient", - "shortName": "ProvisioningAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient.delete_instance", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning.DeleteInstance", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning", - "shortName": "Provisioning" - }, - "shortName": "DeleteInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_instance" - }, - "description": "Sample for DeleteInstance", - "file": "apigeeregistry_v1_generated_provisioning_delete_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Provisioning_DeleteInstance_async", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_provisioning_delete_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient", - "shortName": "ProvisioningClient" - }, - "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient.delete_instance", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning.DeleteInstance", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning", - "shortName": "Provisioning" - }, - "shortName": "DeleteInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteInstanceRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_instance" - }, - "description": "Sample for DeleteInstance", - "file": "apigeeregistry_v1_generated_provisioning_delete_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Provisioning_DeleteInstance_sync", - "segments": [ - { - "end": 55, - "start": 27, - "type": "FULL" - }, - { - "end": 55, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 52, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 56, - "start": 53, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_provisioning_delete_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient", - "shortName": "ProvisioningAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.ProvisioningAsyncClient.get_instance", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning.GetInstance", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning", - "shortName": "Provisioning" - }, - "shortName": "GetInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetInstanceRequest" - }, - { - "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.apigee_registry_v1.types.Instance", - "shortName": "get_instance" - }, - "description": "Sample for GetInstance", - "file": "apigeeregistry_v1_generated_provisioning_get_instance_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Provisioning_GetInstance_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": "apigeeregistry_v1_generated_provisioning_get_instance_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient", - "shortName": "ProvisioningClient" - }, - "fullName": "google.cloud.apigee_registry_v1.ProvisioningClient.get_instance", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning.GetInstance", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Provisioning", - "shortName": "Provisioning" - }, - "shortName": "GetInstance" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetInstanceRequest" - }, - { - "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.apigee_registry_v1.types.Instance", - "shortName": "get_instance" - }, - "description": "Sample for GetInstance", - "file": "apigeeregistry_v1_generated_provisioning_get_instance_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Provisioning_GetInstance_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": "apigeeregistry_v1_generated_provisioning_get_instance_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api_deployment", - "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" - }, - { - "name": "api_deployment_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "create_api_deployment" - }, - "description": "Sample for CreateApiDeployment", - "file": "apigeeregistry_v1_generated_registry_create_api_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiDeployment_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiDeploymentRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api_deployment", - "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" - }, - { - "name": "api_deployment_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "create_api_deployment" - }, - "description": "Sample for CreateApiDeployment", - "file": "apigeeregistry_v1_generated_registry_create_api_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiDeployment_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiSpecRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api_spec", - "type": "google.cloud.apigee_registry_v1.types.ApiSpec" - }, - { - "name": "api_spec_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "create_api_spec" - }, - "description": "Sample for CreateApiSpec", - "file": "apigeeregistry_v1_generated_registry_create_api_spec_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiSpec_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_spec_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiSpecRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api_spec", - "type": "google.cloud.apigee_registry_v1.types.ApiSpec" - }, - { - "name": "api_spec_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "create_api_spec" - }, - "description": "Sample for CreateApiSpec", - "file": "apigeeregistry_v1_generated_registry_create_api_spec_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiSpec_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_spec_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api_version", - "type": "google.cloud.apigee_registry_v1.types.ApiVersion" - }, - { - "name": "api_version_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", - "shortName": "create_api_version" - }, - "description": "Sample for CreateApiVersion", - "file": "apigeeregistry_v1_generated_registry_create_api_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiVersion_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api_version", - "type": "google.cloud.apigee_registry_v1.types.ApiVersion" - }, - { - "name": "api_version_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", - "shortName": "create_api_version" - }, - "description": "Sample for CreateApiVersion", - "file": "apigeeregistry_v1_generated_registry_create_api_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApiVersion_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api", - "type": "google.cloud.apigee_registry_v1.types.Api" - }, - { - "name": "api_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Api", - "shortName": "create_api" - }, - "description": "Sample for CreateApi", - "file": "apigeeregistry_v1_generated_registry_create_api_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApi_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateApiRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "api", - "type": "google.cloud.apigee_registry_v1.types.Api" - }, - { - "name": "api_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Api", - "shortName": "create_api" - }, - "description": "Sample for CreateApi", - "file": "apigeeregistry_v1_generated_registry_create_api_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateApi_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_api_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.create_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateArtifactRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "artifact", - "type": "google.cloud.apigee_registry_v1.types.Artifact" - }, - { - "name": "artifact_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Artifact", - "shortName": "create_artifact" - }, - "description": "Sample for CreateArtifact", - "file": "apigeeregistry_v1_generated_registry_create_artifact_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateArtifact_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_artifact_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.create_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.CreateArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "CreateArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.CreateArtifactRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "artifact", - "type": "google.cloud.apigee_registry_v1.types.Artifact" - }, - { - "name": "artifact_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Artifact", - "shortName": "create_artifact" - }, - "description": "Sample for CreateArtifact", - "file": "apigeeregistry_v1_generated_registry_create_artifact_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_CreateArtifact_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_create_artifact_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_deployment_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeploymentRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiDeploymentRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest" - }, - { - "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.apigee_registry_v1.types.ApiDeployment", - "shortName": "delete_api_deployment_revision" - }, - "description": "Sample for DeleteApiDeploymentRevision", - "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_deployment_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeploymentRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiDeploymentRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRevisionRequest" - }, - { - "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.apigee_registry_v1.types.ApiDeployment", - "shortName": "delete_api_deployment_revision" - }, - "description": "Sample for DeleteApiDeploymentRevision", - "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeploymentRevision_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": "apigeeregistry_v1_generated_registry_delete_api_deployment_revision_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api_deployment" - }, - "description": "Sample for DeleteApiDeployment", - "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeployment_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiDeploymentRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api_deployment" - }, - "description": "Sample for DeleteApiDeployment", - "file": "apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiDeployment_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_spec_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpecRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiSpecRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest" - }, - { - "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.apigee_registry_v1.types.ApiSpec", - "shortName": "delete_api_spec_revision" - }, - "description": "Sample for DeleteApiSpecRevision", - "file": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_spec_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpecRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiSpecRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRevisionRequest" - }, - { - "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.apigee_registry_v1.types.ApiSpec", - "shortName": "delete_api_spec_revision" - }, - "description": "Sample for DeleteApiSpecRevision", - "file": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpecRevision_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": "apigeeregistry_v1_generated_registry_delete_api_spec_revision_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api_spec" - }, - "description": "Sample for DeleteApiSpec", - "file": "apigeeregistry_v1_generated_registry_delete_api_spec_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpec_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_spec_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiSpecRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api_spec" - }, - "description": "Sample for DeleteApiSpec", - "file": "apigeeregistry_v1_generated_registry_delete_api_spec_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiSpec_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_spec_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api_version" - }, - "description": "Sample for DeleteApiVersion", - "file": "apigeeregistry_v1_generated_registry_delete_api_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiVersion_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api_version" - }, - "description": "Sample for DeleteApiVersion", - "file": "apigeeregistry_v1_generated_registry_delete_api_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApiVersion_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api" - }, - "description": "Sample for DeleteApi", - "file": "apigeeregistry_v1_generated_registry_delete_api_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApi_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteApiRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_api" - }, - "description": "Sample for DeleteApi", - "file": "apigeeregistry_v1_generated_registry_delete_api_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteApi_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_api_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.delete_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteArtifactRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_artifact" - }, - "description": "Sample for DeleteArtifact", - "file": "apigeeregistry_v1_generated_registry_delete_artifact_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteArtifact_async", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_artifact_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.delete_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.DeleteArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "DeleteArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.DeleteArtifactRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "shortName": "delete_artifact" - }, - "description": "Sample for DeleteArtifact", - "file": "apigeeregistry_v1_generated_registry_delete_artifact_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_DeleteArtifact_sync", - "segments": [ - { - "end": 49, - "start": 27, - "type": "FULL" - }, - { - "end": 49, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_delete_artifact_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest" - }, - { - "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.apigee_registry_v1.types.ApiDeployment", - "shortName": "get_api_deployment" - }, - "description": "Sample for GetApiDeployment", - "file": "apigeeregistry_v1_generated_registry_get_api_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiDeployment_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": "apigeeregistry_v1_generated_registry_get_api_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiDeploymentRequest" - }, - { - "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.apigee_registry_v1.types.ApiDeployment", - "shortName": "get_api_deployment" - }, - "description": "Sample for GetApiDeployment", - "file": "apigeeregistry_v1_generated_registry_get_api_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiDeployment_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": "apigeeregistry_v1_generated_registry_get_api_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_spec_contents", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpecContents", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiSpecContents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "get_api_spec_contents" - }, - "description": "Sample for GetApiSpecContents", - "file": "apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpecContents_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": "apigeeregistry_v1_generated_registry_get_api_spec_contents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_spec_contents", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpecContents", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiSpecContents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiSpecContentsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "get_api_spec_contents" - }, - "description": "Sample for GetApiSpecContents", - "file": "apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpecContents_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": "apigeeregistry_v1_generated_registry_get_api_spec_contents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiSpecRequest" - }, - { - "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.apigee_registry_v1.types.ApiSpec", - "shortName": "get_api_spec" - }, - "description": "Sample for GetApiSpec", - "file": "apigeeregistry_v1_generated_registry_get_api_spec_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpec_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": "apigeeregistry_v1_generated_registry_get_api_spec_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiSpecRequest" - }, - { - "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.apigee_registry_v1.types.ApiSpec", - "shortName": "get_api_spec" - }, - "description": "Sample for GetApiSpec", - "file": "apigeeregistry_v1_generated_registry_get_api_spec_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiSpec_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": "apigeeregistry_v1_generated_registry_get_api_spec_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiVersionRequest" - }, - { - "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.apigee_registry_v1.types.ApiVersion", - "shortName": "get_api_version" - }, - "description": "Sample for GetApiVersion", - "file": "apigeeregistry_v1_generated_registry_get_api_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiVersion_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": "apigeeregistry_v1_generated_registry_get_api_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiVersionRequest" - }, - { - "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.apigee_registry_v1.types.ApiVersion", - "shortName": "get_api_version" - }, - "description": "Sample for GetApiVersion", - "file": "apigeeregistry_v1_generated_registry_get_api_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApiVersion_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": "apigeeregistry_v1_generated_registry_get_api_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiRequest" - }, - { - "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.apigee_registry_v1.types.Api", - "shortName": "get_api" - }, - "description": "Sample for GetApi", - "file": "apigeeregistry_v1_generated_registry_get_api_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApi_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": "apigeeregistry_v1_generated_registry_get_api_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetApiRequest" - }, - { - "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.apigee_registry_v1.types.Api", - "shortName": "get_api" - }, - "description": "Sample for GetApi", - "file": "apigeeregistry_v1_generated_registry_get_api_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetApi_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": "apigeeregistry_v1_generated_registry_get_api_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_artifact_contents", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifactContents", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetArtifactContents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "get_artifact_contents" - }, - "description": "Sample for GetArtifactContents", - "file": "apigeeregistry_v1_generated_registry_get_artifact_contents_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifactContents_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": "apigeeregistry_v1_generated_registry_get_artifact_contents_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_artifact_contents", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifactContents", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetArtifactContents" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetArtifactContentsRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api.httpbody_pb2.HttpBody", - "shortName": "get_artifact_contents" - }, - "description": "Sample for GetArtifactContents", - "file": "apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifactContents_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": "apigeeregistry_v1_generated_registry_get_artifact_contents_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.get_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetArtifactRequest" - }, - { - "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.apigee_registry_v1.types.Artifact", - "shortName": "get_artifact" - }, - "description": "Sample for GetArtifact", - "file": "apigeeregistry_v1_generated_registry_get_artifact_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifact_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": "apigeeregistry_v1_generated_registry_get_artifact_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.get_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.GetArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "GetArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.GetArtifactRequest" - }, - { - "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.apigee_registry_v1.types.Artifact", - "shortName": "get_artifact" - }, - "description": "Sample for GetArtifact", - "file": "apigeeregistry_v1_generated_registry_get_artifact_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_GetArtifact_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": "apigeeregistry_v1_generated_registry_get_artifact_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_deployment_revisions", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeploymentRevisions", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiDeploymentRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsAsyncPager", - "shortName": "list_api_deployment_revisions" - }, - "description": "Sample for ListApiDeploymentRevisions", - "file": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_deployment_revisions", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeploymentRevisions", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiDeploymentRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentRevisionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiDeploymentRevisionsPager", - "shortName": "list_api_deployment_revisions" - }, - "description": "Sample for ListApiDeploymentRevisions", - "file": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeploymentRevisions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_deployment_revisions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_deployments", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeployments", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiDeployments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsAsyncPager", - "shortName": "list_api_deployments" - }, - "description": "Sample for ListApiDeployments", - "file": "apigeeregistry_v1_generated_registry_list_api_deployments_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeployments_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_deployments_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_deployments", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiDeployments", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiDeployments" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiDeploymentsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApiDeploymentsPager", - "shortName": "list_api_deployments" - }, - "description": "Sample for ListApiDeployments", - "file": "apigeeregistry_v1_generated_registry_list_api_deployments_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiDeployments_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_deployments_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_spec_revisions", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecRevisions", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiSpecRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsAsyncPager", - "shortName": "list_api_spec_revisions" - }, - "description": "Sample for ListApiSpecRevisions", - "file": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_spec_revisions", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecRevisions", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiSpecRevisions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiSpecRevisionsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.services.registry.pagers.ListApiSpecRevisionsPager", - "shortName": "list_api_spec_revisions" - }, - "description": "Sample for ListApiSpecRevisions", - "file": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecRevisions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_spec_revisions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_specs", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecs", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiSpecs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiSpecsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApiSpecsAsyncPager", - "shortName": "list_api_specs" - }, - "description": "Sample for ListApiSpecs", - "file": "apigeeregistry_v1_generated_registry_list_api_specs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecs_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_specs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_specs", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiSpecs", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiSpecs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiSpecsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApiSpecsPager", - "shortName": "list_api_specs" - }, - "description": "Sample for ListApiSpecs", - "file": "apigeeregistry_v1_generated_registry_list_api_specs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiSpecs_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_specs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_api_versions", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiVersions", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiVersionsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApiVersionsAsyncPager", - "shortName": "list_api_versions" - }, - "description": "Sample for ListApiVersions", - "file": "apigeeregistry_v1_generated_registry_list_api_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_api_versions", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApiVersions", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApiVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApiVersionsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApiVersionsPager", - "shortName": "list_api_versions" - }, - "description": "Sample for ListApiVersions", - "file": "apigeeregistry_v1_generated_registry_list_api_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApiVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_api_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_apis", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApis", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApis" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApisRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApisAsyncPager", - "shortName": "list_apis" - }, - "description": "Sample for ListApis", - "file": "apigeeregistry_v1_generated_registry_list_apis_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApis_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_apis_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_apis", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListApis", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListApis" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListApisRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListApisPager", - "shortName": "list_apis" - }, - "description": "Sample for ListApis", - "file": "apigeeregistry_v1_generated_registry_list_apis_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListApis_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_apis_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.list_artifacts", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListArtifacts", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListArtifacts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListArtifactsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListArtifactsAsyncPager", - "shortName": "list_artifacts" - }, - "description": "Sample for ListArtifacts", - "file": "apigeeregistry_v1_generated_registry_list_artifacts_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListArtifacts_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_artifacts_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.list_artifacts", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ListArtifacts", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ListArtifacts" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ListArtifactsRequest" - }, - { - "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.apigee_registry_v1.services.registry.pagers.ListArtifactsPager", - "shortName": "list_artifacts" - }, - "description": "Sample for ListArtifacts", - "file": "apigeeregistry_v1_generated_registry_list_artifacts_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ListArtifacts_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_list_artifacts_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.replace_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ReplaceArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ReplaceArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest" - }, - { - "name": "artifact", - "type": "google.cloud.apigee_registry_v1.types.Artifact" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Artifact", - "shortName": "replace_artifact" - }, - "description": "Sample for ReplaceArtifact", - "file": "apigeeregistry_v1_generated_registry_replace_artifact_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ReplaceArtifact_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_replace_artifact_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.replace_artifact", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.ReplaceArtifact", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "ReplaceArtifact" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.ReplaceArtifactRequest" - }, - { - "name": "artifact", - "type": "google.cloud.apigee_registry_v1.types.Artifact" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Artifact", - "shortName": "replace_artifact" - }, - "description": "Sample for ReplaceArtifact", - "file": "apigeeregistry_v1_generated_registry_replace_artifact_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_ReplaceArtifact_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_replace_artifact_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.rollback_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "RollbackApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "rollback_api_deployment" - }, - "description": "Sample for RollbackApiDeployment", - "file": "apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiDeployment_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_rollback_api_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.rollback_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "RollbackApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.RollbackApiDeploymentRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "rollback_api_deployment" - }, - "description": "Sample for RollbackApiDeployment", - "file": "apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiDeployment_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_rollback_api_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.rollback_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "RollbackApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "rollback_api_spec" - }, - "description": "Sample for RollbackApiSpec", - "file": "apigeeregistry_v1_generated_registry_rollback_api_spec_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiSpec_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_rollback_api_spec_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.rollback_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.RollbackApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "RollbackApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.RollbackApiSpecRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "rollback_api_spec" - }, - "description": "Sample for RollbackApiSpec", - "file": "apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_RollbackApiSpec_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_rollback_api_spec_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.tag_api_deployment_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiDeploymentRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "TagApiDeploymentRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "tag_api_deployment_revision" - }, - "description": "Sample for TagApiDeploymentRevision", - "file": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.tag_api_deployment_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiDeploymentRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "TagApiDeploymentRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.TagApiDeploymentRevisionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "tag_api_deployment_revision" - }, - "description": "Sample for TagApiDeploymentRevision", - "file": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_TagApiDeploymentRevision_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_tag_api_deployment_revision_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.tag_api_spec_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiSpecRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "TagApiSpecRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "tag_api_spec_revision" - }, - "description": "Sample for TagApiSpecRevision", - "file": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_TagApiSpecRevision_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.tag_api_spec_revision", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.TagApiSpecRevision", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "TagApiSpecRevision" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.TagApiSpecRevisionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "tag_api_spec_revision" - }, - "description": "Sample for TagApiSpecRevision", - "file": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_TagApiSpecRevision_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "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": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_tag_api_spec_revision_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest" - }, - { - "name": "api_deployment", - "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "update_api_deployment" - }, - "description": "Sample for UpdateApiDeployment", - "file": "apigeeregistry_v1_generated_registry_update_api_deployment_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiDeployment_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_deployment_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api_deployment", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiDeployment", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApiDeployment" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiDeploymentRequest" - }, - { - "name": "api_deployment", - "type": "google.cloud.apigee_registry_v1.types.ApiDeployment" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiDeployment", - "shortName": "update_api_deployment" - }, - "description": "Sample for UpdateApiDeployment", - "file": "apigeeregistry_v1_generated_registry_update_api_deployment_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiDeployment_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_deployment_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest" - }, - { - "name": "api_spec", - "type": "google.cloud.apigee_registry_v1.types.ApiSpec" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "update_api_spec" - }, - "description": "Sample for UpdateApiSpec", - "file": "apigeeregistry_v1_generated_registry_update_api_spec_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiSpec_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_spec_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api_spec", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiSpec", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApiSpec" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiSpecRequest" - }, - { - "name": "api_spec", - "type": "google.cloud.apigee_registry_v1.types.ApiSpec" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiSpec", - "shortName": "update_api_spec" - }, - "description": "Sample for UpdateApiSpec", - "file": "apigeeregistry_v1_generated_registry_update_api_spec_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiSpec_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_spec_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest" - }, - { - "name": "api_version", - "type": "google.cloud.apigee_registry_v1.types.ApiVersion" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", - "shortName": "update_api_version" - }, - "description": "Sample for UpdateApiVersion", - "file": "apigeeregistry_v1_generated_registry_update_api_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiVersion_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api_version", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApiVersion", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApiVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiVersionRequest" - }, - { - "name": "api_version", - "type": "google.cloud.apigee_registry_v1.types.ApiVersion" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.ApiVersion", - "shortName": "update_api_version" - }, - "description": "Sample for UpdateApiVersion", - "file": "apigeeregistry_v1_generated_registry_update_api_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApiVersion_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient", - "shortName": "RegistryAsyncClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryAsyncClient.update_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiRequest" - }, - { - "name": "api", - "type": "google.cloud.apigee_registry_v1.types.Api" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Api", - "shortName": "update_api" - }, - "description": "Sample for UpdateApi", - "file": "apigeeregistry_v1_generated_registry_update_api_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApi_async", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.apigee_registry_v1.RegistryClient", - "shortName": "RegistryClient" - }, - "fullName": "google.cloud.apigee_registry_v1.RegistryClient.update_api", - "method": { - "fullName": "google.cloud.apigeeregistry.v1.Registry.UpdateApi", - "service": { - "fullName": "google.cloud.apigeeregistry.v1.Registry", - "shortName": "Registry" - }, - "shortName": "UpdateApi" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.apigee_registry_v1.types.UpdateApiRequest" - }, - { - "name": "api", - "type": "google.cloud.apigee_registry_v1.types.Api" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.apigee_registry_v1.types.Api", - "shortName": "update_api" - }, - "description": "Sample for UpdateApi", - "file": "apigeeregistry_v1_generated_registry_update_api_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "apigeeregistry_v1_generated_Registry_UpdateApi_sync", - "segments": [ - { - "end": 50, - "start": 27, - "type": "FULL" - }, - { - "end": 50, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 44, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 47, - "start": 45, - "type": "REQUEST_EXECUTION" - }, - { - "end": 51, - "start": 48, - "type": "RESPONSE_HANDLING" - } - ], - "title": "apigeeregistry_v1_generated_registry_update_api_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py deleted file mode 100644 index e82af4a..0000000 --- a/owl-bot-staging/v1/scripts/fixup_apigee_registry_v1_keywords.py +++ /dev/null @@ -1,213 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class apigee_registryCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_api': ('parent', 'api', 'api_id', ), - 'create_api_deployment': ('parent', 'api_deployment', 'api_deployment_id', ), - 'create_api_spec': ('parent', 'api_spec', 'api_spec_id', ), - 'create_api_version': ('parent', 'api_version', 'api_version_id', ), - 'create_artifact': ('parent', 'artifact', 'artifact_id', ), - 'create_instance': ('parent', 'instance_id', 'instance', ), - 'delete_api': ('name', 'force', ), - 'delete_api_deployment': ('name', 'force', ), - 'delete_api_deployment_revision': ('name', ), - 'delete_api_spec': ('name', 'force', ), - 'delete_api_spec_revision': ('name', ), - 'delete_api_version': ('name', 'force', ), - 'delete_artifact': ('name', ), - 'delete_instance': ('name', ), - 'get_api': ('name', ), - 'get_api_deployment': ('name', ), - 'get_api_spec': ('name', ), - 'get_api_spec_contents': ('name', ), - 'get_api_version': ('name', ), - 'get_artifact': ('name', ), - 'get_artifact_contents': ('name', ), - 'get_instance': ('name', ), - 'list_api_deployment_revisions': ('name', 'page_size', 'page_token', ), - 'list_api_deployments': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_apis': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_api_spec_revisions': ('name', 'page_size', 'page_token', ), - 'list_api_specs': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_api_versions': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_artifacts': ('parent', 'page_size', 'page_token', 'filter', ), - 'replace_artifact': ('artifact', ), - 'rollback_api_deployment': ('name', 'revision_id', ), - 'rollback_api_spec': ('name', 'revision_id', ), - 'tag_api_deployment_revision': ('name', 'tag', ), - 'tag_api_spec_revision': ('name', 'tag', ), - 'update_api': ('api', 'update_mask', 'allow_missing', ), - 'update_api_deployment': ('api_deployment', 'update_mask', 'allow_missing', ), - 'update_api_spec': ('api_spec', 'update_mask', 'allow_missing', ), - 'update_api_version': ('api_version', 'update_mask', 'allow_missing', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: a.keyword.value not in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), -cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=apigee_registryCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the apigee_registry client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/owl-bot-staging/v1/setup.py b/owl-bot-staging/v1/setup.py deleted file mode 100644 index 01aa9ca..0000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- 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. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-apigee-registry' - - -description = "Google Cloud Apigee Registry API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/apigee_registry/gapic_version.py')) as fp: - exec(fp.read(), version) -version = version["__version__"] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -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', -] -url = "https://github.com/googleapis/python-apigee-registry" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") -] - -namespaces = ["google", "google.cloud"] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.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", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - namespace_packages=namespaces, - install_requires=dependencies, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/v1/testing/constraints-3.10.txt b/owl-bot-staging/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.11.txt b/owl-bot-staging/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.12.txt b/owl-bot-staging/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.7.txt b/owl-bot-staging/v1/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf9..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,10 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -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/owl-bot-staging/v1/testing/constraints-3.8.txt b/owl-bot-staging/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- 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 diff --git a/owl-bot-staging/v1/testing/constraints-3.9.txt b/owl-bot-staging/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa..0000000 --- a/owl-bot-staging/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +0,0 @@ -# -*- 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 diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/__init__.py b/owl-bot-staging/v1/tests/unit/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py deleted file mode 100644 index 231bc12..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- 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. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py deleted file mode 100644 index d5039bd..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_provisioning.py +++ /dev/null @@ -1,4396 +0,0 @@ -# -*- 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. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.apigee_registry_v1.services.provisioning import ProvisioningAsyncClient -from google.cloud.apigee_registry_v1.services.provisioning import ProvisioningClient -from google.cloud.apigee_registry_v1.services.provisioning import transports -from google.cloud.apigee_registry_v1.types import provisioning_service -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 empty_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert ProvisioningClient._get_default_mtls_endpoint(None) is None - assert ProvisioningClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert ProvisioningClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert ProvisioningClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert ProvisioningClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert ProvisioningClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProvisioningClient, "grpc"), - (ProvisioningAsyncClient, "grpc_asyncio"), - (ProvisioningClient, "rest"), -]) -def test_provisioning_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://apigeeregistry.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.ProvisioningGrpcTransport, "grpc"), - (transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.ProvisioningRestTransport, "rest"), -]) -def test_provisioning_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (ProvisioningClient, "grpc"), - (ProvisioningAsyncClient, "grpc_asyncio"), - (ProvisioningClient, "rest"), -]) -def test_provisioning_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://apigeeregistry.googleapis.com' - ) - - -def test_provisioning_client_get_transport_class(): - transport = ProvisioningClient.get_transport_class() - available_transports = [ - transports.ProvisioningGrpcTransport, - transports.ProvisioningRestTransport, - ] - assert transport in available_transports - - transport = ProvisioningClient.get_transport_class("grpc") - assert transport == transports.ProvisioningGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc"), - (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio"), - (ProvisioningClient, transports.ProvisioningRestTransport, "rest"), -]) -@mock.patch.object(ProvisioningClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningClient)) -@mock.patch.object(ProvisioningAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningAsyncClient)) -def test_provisioning_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(ProvisioningClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(ProvisioningClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", "true"), - (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", "false"), - (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (ProvisioningClient, transports.ProvisioningRestTransport, "rest", "true"), - (ProvisioningClient, transports.ProvisioningRestTransport, "rest", "false"), -]) -@mock.patch.object(ProvisioningClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningClient)) -@mock.patch.object(ProvisioningAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_provisioning_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - ProvisioningClient, ProvisioningAsyncClient -]) -@mock.patch.object(ProvisioningClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningClient)) -@mock.patch.object(ProvisioningAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProvisioningAsyncClient)) -def test_provisioning_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc"), - (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio"), - (ProvisioningClient, transports.ProvisioningRestTransport, "rest"), -]) -def test_provisioning_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", grpc_helpers), - (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (ProvisioningClient, transports.ProvisioningRestTransport, "rest", None), -]) -def test_provisioning_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_provisioning_client_client_options_from_dict(): - with mock.patch('google.cloud.apigee_registry_v1.services.provisioning.transports.ProvisioningGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = ProvisioningClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (ProvisioningClient, transports.ProvisioningGrpcTransport, "grpc", grpc_helpers), - (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_provisioning_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "apigeeregistry.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="apigeeregistry.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - provisioning_service.CreateInstanceRequest, - dict, -]) -def test_create_instance(request_type, transport: str = 'grpc'): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.CreateInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_instance_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 = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - client.create_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.CreateInstanceRequest() - -@pytest.mark.asyncio -async def test_create_instance_async(transport: str = 'grpc_asyncio', request_type=provisioning_service.CreateInstanceRequest): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.create_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.CreateInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_instance_async_from_dict(): - await test_create_instance_async(request_type=dict) - - -def test_create_instance_field_headers(): - client = ProvisioningClient( - 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 = provisioning_service.CreateInstanceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_instance_field_headers_async(): - client = ProvisioningAsyncClient( - 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 = provisioning_service.CreateInstanceRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_instance_flattened(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_instance( - parent='parent_value', - instance=provisioning_service.Instance(name='name_value'), - instance_id='instance_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].instance - mock_val = provisioning_service.Instance(name='name_value') - assert arg == mock_val - arg = args[0].instance_id - mock_val = 'instance_id_value' - assert arg == mock_val - - -def test_create_instance_flattened_error(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_instance( - provisioning_service.CreateInstanceRequest(), - parent='parent_value', - instance=provisioning_service.Instance(name='name_value'), - instance_id='instance_id_value', - ) - -@pytest.mark.asyncio -async def test_create_instance_flattened_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_instance( - parent='parent_value', - instance=provisioning_service.Instance(name='name_value'), - instance_id='instance_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].instance - mock_val = provisioning_service.Instance(name='name_value') - assert arg == mock_val - arg = args[0].instance_id - mock_val = 'instance_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_instance_flattened_error_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_instance( - provisioning_service.CreateInstanceRequest(), - parent='parent_value', - instance=provisioning_service.Instance(name='name_value'), - instance_id='instance_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - provisioning_service.DeleteInstanceRequest, - dict, -]) -def test_delete_instance(request_type, transport: str = 'grpc'): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.DeleteInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_instance_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 = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - client.delete_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.DeleteInstanceRequest() - -@pytest.mark.asyncio -async def test_delete_instance_async(transport: str = 'grpc_asyncio', request_type=provisioning_service.DeleteInstanceRequest): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - response = await client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.DeleteInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_delete_instance_async_from_dict(): - await test_delete_instance_async(request_type=dict) - - -def test_delete_instance_field_headers(): - client = ProvisioningClient( - 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 = provisioning_service.DeleteInstanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_instance_field_headers_async(): - client = ProvisioningAsyncClient( - 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 = provisioning_service.DeleteInstanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_instance_flattened(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_instance( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_instance_flattened_error(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_instance( - provisioning_service.DeleteInstanceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_instance_flattened_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/op') - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_instance( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_instance_flattened_error_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_instance( - provisioning_service.DeleteInstanceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - provisioning_service.GetInstanceRequest, - dict, -]) -def test_get_instance(request_type, transport: str = 'grpc'): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = provisioning_service.Instance( - name='name_value', - state=provisioning_service.Instance.State.INACTIVE, - state_message='state_message_value', - ) - response = client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.GetInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, provisioning_service.Instance) - assert response.name == 'name_value' - assert response.state == provisioning_service.Instance.State.INACTIVE - assert response.state_message == 'state_message_value' - - -def test_get_instance_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 = ProvisioningClient( - 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_instance), - '__call__') as call: - client.get_instance() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.GetInstanceRequest() - -@pytest.mark.asyncio -async def test_get_instance_async(transport: str = 'grpc_asyncio', request_type=provisioning_service.GetInstanceRequest): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(provisioning_service.Instance( - name='name_value', - state=provisioning_service.Instance.State.INACTIVE, - state_message='state_message_value', - )) - response = await client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == provisioning_service.GetInstanceRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, provisioning_service.Instance) - assert response.name == 'name_value' - assert response.state == provisioning_service.Instance.State.INACTIVE - assert response.state_message == 'state_message_value' - - -@pytest.mark.asyncio -async def test_get_instance_async_from_dict(): - await test_get_instance_async(request_type=dict) - - -def test_get_instance_field_headers(): - client = ProvisioningClient( - 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 = provisioning_service.GetInstanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - call.return_value = provisioning_service.Instance() - client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_instance_field_headers_async(): - client = ProvisioningAsyncClient( - 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 = provisioning_service.GetInstanceRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(provisioning_service.Instance()) - await client.get_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_instance_flattened(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = provisioning_service.Instance() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_instance( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_instance_flattened_error(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_instance( - provisioning_service.GetInstanceRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_instance_flattened_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_instance), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = provisioning_service.Instance() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(provisioning_service.Instance()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_instance( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_instance_flattened_error_async(): - client = ProvisioningAsyncClient( - 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_instance( - provisioning_service.GetInstanceRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - provisioning_service.CreateInstanceRequest, - dict, -]) -def test_create_instance_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["instance"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 1, 'state_message': 'state_message_value', 'config': {'location': 'location_value', 'cmek_key_name': 'cmek_key_name_value'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_create_instance_rest_required_fields(request_type=provisioning_service.CreateInstanceRequest): - transport_class = transports.ProvisioningRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "instanceId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["instanceId"] = 'instance_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("instance_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == 'instance_id_value' - - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_instance(request) - - expected_params = [ - ( - "instanceId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_instance_rest_unset_required_fields(): - transport = transports.ProvisioningRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("instanceId", )) & set(("parent", "instanceId", "instance", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): - transport = transports.ProvisioningRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProvisioningRestInterceptor(), - ) - client = ProvisioningClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ProvisioningRestInterceptor, "post_create_instance") as post, \ - mock.patch.object(transports.ProvisioningRestInterceptor, "pre_create_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = provisioning_service.CreateInstanceRequest.pb(provisioning_service.CreateInstanceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = provisioning_service.CreateInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_instance_rest_bad_request(transport: str = 'rest', request_type=provisioning_service.CreateInstanceRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["instance"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 1, 'state_message': 'state_message_value', 'config': {'location': 'location_value', 'cmek_key_name': 'cmek_key_name_value'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_instance(request) - - -def test_create_instance_rest_flattened(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - instance=provisioning_service.Instance(name='name_value'), - instance_id='instance_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/instances" % client.transport._host, args[1]) - - -def test_create_instance_rest_flattened_error(transport: str = 'rest'): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_instance( - provisioning_service.CreateInstanceRequest(), - parent='parent_value', - instance=provisioning_service.Instance(name='name_value'), - instance_id='instance_id_value', - ) - - -def test_create_instance_rest_error(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - provisioning_service.DeleteInstanceRequest, - dict, -]) -def test_delete_instance_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_instance(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_delete_instance_rest_required_fields(request_type=provisioning_service.DeleteInstanceRequest): - transport_class = transports.ProvisioningRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_instance(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_instance_rest_unset_required_fields(): - transport = transports.ProvisioningRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): - transport = transports.ProvisioningRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProvisioningRestInterceptor(), - ) - client = ProvisioningClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(operation.Operation, "_set_result_from_operation"), \ - mock.patch.object(transports.ProvisioningRestInterceptor, "post_delete_instance") as post, \ - mock.patch.object(transports.ProvisioningRestInterceptor, "pre_delete_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = provisioning_service.DeleteInstanceRequest.pb(provisioning_service.DeleteInstanceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(operations_pb2.Operation()) - - request = provisioning_service.DeleteInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.delete_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_instance_rest_bad_request(transport: str = 'rest', request_type=provisioning_service.DeleteInstanceRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_instance(request) - - -def test_delete_instance_rest_flattened(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) - - -def test_delete_instance_rest_flattened_error(transport: str = 'rest'): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_instance( - provisioning_service.DeleteInstanceRequest(), - name='name_value', - ) - - -def test_delete_instance_rest_error(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - provisioning_service.GetInstanceRequest, - dict, -]) -def test_get_instance_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = provisioning_service.Instance( - name='name_value', - state=provisioning_service.Instance.State.INACTIVE, - state_message='state_message_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = provisioning_service.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_instance(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, provisioning_service.Instance) - assert response.name == 'name_value' - assert response.state == provisioning_service.Instance.State.INACTIVE - assert response.state_message == 'state_message_value' - - -def test_get_instance_rest_required_fields(request_type=provisioning_service.GetInstanceRequest): - transport_class = transports.ProvisioningRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = provisioning_service.Instance() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = provisioning_service.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_instance(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_instance_rest_unset_required_fields(): - transport = transports.ProvisioningRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): - transport = transports.ProvisioningRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.ProvisioningRestInterceptor(), - ) - client = ProvisioningClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.ProvisioningRestInterceptor, "post_get_instance") as post, \ - mock.patch.object(transports.ProvisioningRestInterceptor, "pre_get_instance") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = provisioning_service.GetInstanceRequest.pb(provisioning_service.GetInstanceRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = provisioning_service.Instance.to_json(provisioning_service.Instance()) - - request = provisioning_service.GetInstanceRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = provisioning_service.Instance() - - client.get_instance(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_instance_rest_bad_request(transport: str = 'rest', request_type=provisioning_service.GetInstanceRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_instance(request) - - -def test_get_instance_rest_flattened(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = provisioning_service.Instance() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/instances/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = provisioning_service.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/instances/*}" % client.transport._host, args[1]) - - -def test_get_instance_rest_flattened_error(transport: str = 'rest'): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_instance( - provisioning_service.GetInstanceRequest(), - name='name_value', - ) - - -def test_get_instance_rest_error(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ProvisioningGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.ProvisioningGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProvisioningClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.ProvisioningGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ProvisioningClient( - 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 = ProvisioningClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.ProvisioningGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ProvisioningClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProvisioningGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = ProvisioningClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ProvisioningGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.ProvisioningGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.ProvisioningGrpcTransport, - transports.ProvisioningGrpcAsyncIOTransport, - transports.ProvisioningRestTransport, -]) -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", - "rest", -]) -def test_transport_kind(transport_name): - transport = ProvisioningClient.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 = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.ProvisioningGrpcTransport, - ) - -def test_provisioning_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ProvisioningTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_provisioning_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.apigee_registry_v1.services.provisioning.transports.ProvisioningTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.ProvisioningTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_instance', - 'delete_instance', - 'get_instance', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - '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_provisioning_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.apigee_registry_v1.services.provisioning.transports.ProvisioningTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProvisioningTransport( - 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_provisioning_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.apigee_registry_v1.services.provisioning.transports.ProvisioningTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.ProvisioningTransport() - adc.assert_called_once() - - -def test_provisioning_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) - ProvisioningClient() - 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.ProvisioningGrpcTransport, - transports.ProvisioningGrpcAsyncIOTransport, - ], -) -def test_provisioning_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.ProvisioningGrpcTransport, - transports.ProvisioningGrpcAsyncIOTransport, - transports.ProvisioningRestTransport, - ], -) -def test_provisioning_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.ProvisioningGrpcTransport, grpc_helpers), - (transports.ProvisioningGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_provisioning_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( - "apigeeregistry.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="apigeeregistry.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.ProvisioningGrpcTransport, transports.ProvisioningGrpcAsyncIOTransport]) -def test_provisioning_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 - ) - -def test_provisioning_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.ProvisioningRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -def test_provisioning_rest_lro_client(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_provisioning_host_no_port(transport_name): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://apigeeregistry.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_provisioning_host_with_port(transport_name): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://apigeeregistry.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_provisioning_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = ProvisioningClient( - credentials=creds1, - transport=transport_name, - ) - client2 = ProvisioningClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_instance._session - session2 = client2.transport.create_instance._session - assert session1 != session2 - session1 = client1.transport.delete_instance._session - session2 = client2.transport.delete_instance._session - assert session1 != session2 - session1 = client1.transport.get_instance._session - session2 = client2.transport.get_instance._session - assert session1 != session2 -def test_provisioning_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProvisioningGrpcTransport( - 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_provisioning_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.ProvisioningGrpcAsyncIOTransport( - 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.ProvisioningGrpcTransport, transports.ProvisioningGrpcAsyncIOTransport]) -def test_provisioning_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.ProvisioningGrpcTransport, transports.ProvisioningGrpcAsyncIOTransport]) -def test_provisioning_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_provisioning_grpc_lro_client(): - client = ProvisioningClient( - 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_provisioning_grpc_lro_async_client(): - client = ProvisioningAsyncClient( - 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_instance_path(): - project = "squid" - location = "clam" - instance = "whelk" - expected = "projects/{project}/locations/{location}/instances/{instance}".format(project=project, location=location, instance=instance, ) - actual = ProvisioningClient.instance_path(project, location, instance) - assert expected == actual - - -def test_parse_instance_path(): - expected = { - "project": "octopus", - "location": "oyster", - "instance": "nudibranch", - } - path = ProvisioningClient.instance_path(**expected) - - # Check that the path construction is reversible. - actual = ProvisioningClient.parse_instance_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = ProvisioningClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = ProvisioningClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = ProvisioningClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = ProvisioningClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = ProvisioningClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = ProvisioningClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = ProvisioningClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = ProvisioningClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = ProvisioningClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = ProvisioningClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = ProvisioningClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = ProvisioningClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "whelk" - location = "octopus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = ProvisioningClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = ProvisioningClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = ProvisioningClient.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(transports.ProvisioningTransport, '_prep_wrapped_messages') as prep: - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.ProvisioningTransport, '_prep_wrapped_messages') as prep: - transport_class = ProvisioningClient.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 = ProvisioningAsyncClient( - 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = ProvisioningClient( - 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 = ProvisioningAsyncClient( - 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 = ProvisioningClient( - 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 = ProvisioningAsyncClient( - 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 = ProvisioningClient( - 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 = ProvisioningAsyncClient( - 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 = ProvisioningClient( - 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 = ProvisioningAsyncClient( - 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 = ProvisioningClient( - 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 = ProvisioningAsyncClient( - 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"] - -def test_cancel_operation_from_dict(): - client = ProvisioningClient( - 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 - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = ProvisioningAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = ProvisioningClient( - 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.GetOperationRequest() - - # 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 - - # 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 = ProvisioningAsyncClient( - 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.GetOperationRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = ProvisioningClient( - 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.GetOperationRequest() - request.name = "locations" - - # 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() - - 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 - - # 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_get_operation_field_headers_async(): - client = ProvisioningAsyncClient( - 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.GetOperationRequest() - request.name = "locations" - - # 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # 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={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # 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() - - -def test_list_operations(transport: str = "grpc"): - client = ProvisioningClient( - 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.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 - - # 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 = ProvisioningAsyncClient( - 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.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 = 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = ProvisioningClient( - 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.ListOperationsRequest() - request.name = "locations" - - # 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() - - 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"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = ProvisioningAsyncClient( - 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.ListOperationsRequest() - request.name = "locations" - - # 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = ProvisioningClient( - 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 = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = ProvisioningAsyncClient( - 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_list_locations(transport: str = "grpc"): - client = ProvisioningClient( - 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 = locations_pb2.ListLocationsRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = ProvisioningAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = ProvisioningClient( - 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.ListLocationsRequest() - request.name = "locations" - - # 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() - - 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"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = ProvisioningAsyncClient( - 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.ListLocationsRequest() - request.name = "locations" - - # 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = ProvisioningClient( - 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.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = ProvisioningAsyncClient( - 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_get_location(transport: str = "grpc"): - client = ProvisioningClient( - 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 = locations_pb2.GetLocationRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = ProvisioningAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = ProvisioningClient( - 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" - - # 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() - - 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"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = ProvisioningAsyncClient( - 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" - - # 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_get_location_from_dict(): - client = ProvisioningClient( - 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() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = ProvisioningAsyncClient( - 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.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = ProvisioningClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = ProvisioningAsyncClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = ProvisioningClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = ProvisioningAsyncClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = ProvisioningClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = ProvisioningAsyncClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = ProvisioningClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = ProvisioningAsyncClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = ProvisioningClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = ProvisioningAsyncClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = ProvisioningClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = ProvisioningAsyncClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = ProvisioningAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = ProvisioningClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (ProvisioningClient, transports.ProvisioningGrpcTransport), - (ProvisioningAsyncClient, transports.ProvisioningGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py b/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py deleted file mode 100644 index 4f87d0d..0000000 --- a/owl-bot-staging/v1/tests/unit/gapic/apigee_registry_v1/test_registry.py +++ /dev/null @@ -1,21303 +0,0 @@ -# -*- 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. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable -from google.protobuf import json_format -import json -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -from google.api import httpbody_pb2 # type: ignore -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.apigee_registry_v1.services.registry import RegistryAsyncClient -from google.cloud.apigee_registry_v1.services.registry import RegistryClient -from google.cloud.apigee_registry_v1.services.registry import pagers -from google.cloud.apigee_registry_v1.services.registry import transports -from google.cloud.apigee_registry_v1.types import registry_models -from google.cloud.apigee_registry_v1.types import registry_service -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 -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RegistryClient._get_default_mtls_endpoint(None) is None - assert RegistryClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert RegistryClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert RegistryClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert RegistryClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert RegistryClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RegistryClient, "grpc"), - (RegistryAsyncClient, "grpc_asyncio"), - (RegistryClient, "rest"), -]) -def test_registry_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://apigeeregistry.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.RegistryGrpcTransport, "grpc"), - (transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.RegistryRestTransport, "rest"), -]) -def test_registry_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (RegistryClient, "grpc"), - (RegistryAsyncClient, "grpc_asyncio"), - (RegistryClient, "rest"), -]) -def test_registry_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://apigeeregistry.googleapis.com' - ) - - -def test_registry_client_get_transport_class(): - transport = RegistryClient.get_transport_class() - available_transports = [ - transports.RegistryGrpcTransport, - transports.RegistryRestTransport, - ] - assert transport in available_transports - - transport = RegistryClient.get_transport_class("grpc") - assert transport == transports.RegistryGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistryClient, transports.RegistryGrpcTransport, "grpc"), - (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio"), - (RegistryClient, transports.RegistryRestTransport, "rest"), -]) -@mock.patch.object(RegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryClient)) -@mock.patch.object(RegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryAsyncClient)) -def test_registry_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(RegistryClient, 'get_transport_class') as gtc: - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(RegistryClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class(transport=transport_name) - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError): - client = client_class(transport=transport_name) - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (RegistryClient, transports.RegistryGrpcTransport, "grpc", "true"), - (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (RegistryClient, transports.RegistryGrpcTransport, "grpc", "false"), - (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (RegistryClient, transports.RegistryRestTransport, "rest", "true"), - (RegistryClient, transports.RegistryRestTransport, "rest", "false"), -]) -@mock.patch.object(RegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryClient)) -@mock.patch.object(RegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_registry_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client.DEFAULT_ENDPOINT - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - RegistryClient, RegistryAsyncClient -]) -@mock.patch.object(RegistryClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryClient)) -@mock.patch.object(RegistryAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(RegistryAsyncClient)) -def test_registry_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (RegistryClient, transports.RegistryGrpcTransport, "grpc"), - (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio"), - (RegistryClient, transports.RegistryRestTransport, "rest"), -]) -def test_registry_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegistryClient, transports.RegistryGrpcTransport, "grpc", grpc_helpers), - (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (RegistryClient, transports.RegistryRestTransport, "rest", None), -]) -def test_registry_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_registry_client_client_options_from_dict(): - with mock.patch('google.cloud.apigee_registry_v1.services.registry.transports.RegistryGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = RegistryClient( - client_options={'api_endpoint': 'squid.clam.whelk'} - ) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (RegistryClient, transports.RegistryGrpcTransport, "grpc", grpc_helpers), - (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_registry_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "apigeeregistry.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - scopes=None, - default_host="apigeeregistry.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApisRequest, - dict, -]) -def test_list_apis(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApisResponse( - next_page_token='next_page_token_value', - ) - response = client.list_apis(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApisRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApisPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_apis_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__') as call: - client.list_apis() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApisRequest() - -@pytest.mark.asyncio -async def test_list_apis_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApisRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApisResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_apis(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApisRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApisAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_apis_async_from_dict(): - await test_list_apis_async(request_type=dict) - - -def test_list_apis_field_headers(): - client = RegistryClient( - 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 = registry_service.ListApisRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__') as call: - call.return_value = registry_service.ListApisResponse() - client.list_apis(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_apis_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ListApisRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApisResponse()) - await client.list_apis(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_apis_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApisResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_apis( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_apis_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_apis( - registry_service.ListApisRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_apis_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApisResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApisResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_apis( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_apis_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_apis( - registry_service.ListApisRequest(), - parent='parent_value', - ) - - -def test_list_apis_pager(transport_name: str = "grpc"): - client = RegistryClient( - 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_apis), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - registry_models.Api(), - ], - next_page_token='abc', - ), - registry_service.ListApisResponse( - apis=[], - next_page_token='def', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - ], - next_page_token='ghi', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_apis(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.Api) - for i in results) -def test_list_apis_pages(transport_name: str = "grpc"): - client = RegistryClient( - 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_apis), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - registry_models.Api(), - ], - next_page_token='abc', - ), - registry_service.ListApisResponse( - apis=[], - next_page_token='def', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - ], - next_page_token='ghi', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - ], - ), - RuntimeError, - ) - pages = list(client.list_apis(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_apis_async_pager(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - registry_models.Api(), - ], - next_page_token='abc', - ), - registry_service.ListApisResponse( - apis=[], - next_page_token='def', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - ], - next_page_token='ghi', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_apis(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, registry_models.Api) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_apis_async_pages(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_apis), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - registry_models.Api(), - ], - next_page_token='abc', - ), - registry_service.ListApisResponse( - apis=[], - next_page_token='def', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - ], - next_page_token='ghi', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_apis(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("request_type", [ - registry_service.GetApiRequest, - dict, -]) -def test_get_api(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - ) - response = client.get_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -def test_get_api_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 = RegistryClient( - 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_api), - '__call__') as call: - client.get_api() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiRequest() - -@pytest.mark.asyncio -async def test_get_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiRequest): - client = RegistryAsyncClient( - 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_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - )) - response = await client.get_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -@pytest.mark.asyncio -async def test_get_api_async_from_dict(): - await test_get_api_async(request_type=dict) - - -def test_get_api_field_headers(): - client = RegistryClient( - 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 = registry_service.GetApiRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api), - '__call__') as call: - call.return_value = registry_models.Api() - client.get_api(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_api_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.GetApiRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) - await client.get_api(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_api_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_api( - 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_api_flattened_error(): - client = RegistryClient( - 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_api( - registry_service.GetApiRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_api_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_api( - 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_api_flattened_error_async(): - client = RegistryAsyncClient( - 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_api( - registry_service.GetApiRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiRequest, - dict, -]) -def test_create_api(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - ) - response = client.create_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -def test_create_api_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api), - '__call__') as call: - client.create_api() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiRequest() - -@pytest.mark.asyncio -async def test_create_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - )) - response = await client.create_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -@pytest.mark.asyncio -async def test_create_api_async_from_dict(): - await test_create_api_async(request_type=dict) - - -def test_create_api_field_headers(): - client = RegistryClient( - 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 = registry_service.CreateApiRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api), - '__call__') as call: - call.return_value = registry_models.Api() - client.create_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_api_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.CreateApiRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) - await client.create_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_api_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_api( - parent='parent_value', - api=registry_models.Api(name='name_value'), - api_id='api_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api - mock_val = registry_models.Api(name='name_value') - assert arg == mock_val - arg = args[0].api_id - mock_val = 'api_id_value' - assert arg == mock_val - - -def test_create_api_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api( - registry_service.CreateApiRequest(), - parent='parent_value', - api=registry_models.Api(name='name_value'), - api_id='api_id_value', - ) - -@pytest.mark.asyncio -async def test_create_api_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_api( - parent='parent_value', - api=registry_models.Api(name='name_value'), - api_id='api_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api - mock_val = registry_models.Api(name='name_value') - assert arg == mock_val - arg = args[0].api_id - mock_val = 'api_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_api_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_api( - registry_service.CreateApiRequest(), - parent='parent_value', - api=registry_models.Api(name='name_value'), - api_id='api_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiRequest, - dict, -]) -def test_update_api(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - ) - response = client.update_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -def test_update_api_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api), - '__call__') as call: - client.update_api() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiRequest() - -@pytest.mark.asyncio -async def test_update_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - )) - response = await client.update_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -@pytest.mark.asyncio -async def test_update_api_async_from_dict(): - await test_update_api_async(request_type=dict) - - -def test_update_api_field_headers(): - client = RegistryClient( - 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 = registry_service.UpdateApiRequest() - - request.api.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api), - '__call__') as call: - call.return_value = registry_models.Api() - client.update_api(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', - 'api.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_api_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.UpdateApiRequest() - - request.api.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) - await client.update_api(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', - 'api.name=name_value', - ) in kw['metadata'] - - -def test_update_api_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_api( - api=registry_models.Api(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].api - mock_val = registry_models.Api(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_api_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api( - registry_service.UpdateApiRequest(), - api=registry_models.Api(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_api_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Api() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Api()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_api( - api=registry_models.Api(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].api - mock_val = registry_models.Api(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_api_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_api( - registry_service.UpdateApiRequest(), - api=registry_models.Api(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiRequest, - dict, -]) -def test_delete_api(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api), - '__call__') as call: - client.delete_api() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiRequest() - -@pytest.mark.asyncio -async def test_delete_api_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_api_async_from_dict(): - await test_delete_api_async(request_type=dict) - - -def test_delete_api_field_headers(): - client = RegistryClient( - 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 = registry_service.DeleteApiRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api), - '__call__') as call: - call.return_value = None - client.delete_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_api_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.DeleteApiRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_api(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_api_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_api( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_api_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api( - registry_service.DeleteApiRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_api_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_api( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_api_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_api( - registry_service.DeleteApiRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiVersionsRequest, - dict, -]) -def test_list_api_versions(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiVersionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_api_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_versions_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__') as call: - client.list_api_versions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiVersionsRequest() - -@pytest.mark.asyncio -async def test_list_api_versions_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiVersionsRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiVersionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_api_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiVersionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_api_versions_async_from_dict(): - await test_list_api_versions_async(request_type=dict) - - -def test_list_api_versions_field_headers(): - client = RegistryClient( - 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 = registry_service.ListApiVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__') as call: - call.return_value = registry_service.ListApiVersionsResponse() - client.list_api_versions(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_api_versions_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ListApiVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiVersionsResponse()) - await client.list_api_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_api_versions_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_api_versions( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_api_versions_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_api_versions( - registry_service.ListApiVersionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_api_versions_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_api_versions( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_api_versions_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_api_versions( - registry_service.ListApiVersionsRequest(), - parent='parent_value', - ) - - -def test_list_api_versions_pager(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - next_page_token='abc', - ), - registry_service.ListApiVersionsResponse( - api_versions=[], - next_page_token='def', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - ], - next_page_token='ghi', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_api_versions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiVersion) - for i in results) -def test_list_api_versions_pages(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - next_page_token='abc', - ), - registry_service.ListApiVersionsResponse( - api_versions=[], - next_page_token='def', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - ], - next_page_token='ghi', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_api_versions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_api_versions_async_pager(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - next_page_token='abc', - ), - registry_service.ListApiVersionsResponse( - api_versions=[], - next_page_token='def', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - ], - next_page_token='ghi', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_api_versions(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, registry_models.ApiVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_api_versions_async_pages(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - next_page_token='abc', - ), - registry_service.ListApiVersionsResponse( - api_versions=[], - next_page_token='def', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - ], - next_page_token='ghi', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_api_versions(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("request_type", [ - registry_service.GetApiVersionRequest, - dict, -]) -def test_get_api_version(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - ) - response = client.get_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -def test_get_api_version_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 = RegistryClient( - 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_api_version), - '__call__') as call: - client.get_api_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiVersionRequest() - -@pytest.mark.asyncio -async def test_get_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiVersionRequest): - client = RegistryAsyncClient( - 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_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - )) - response = await client.get_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -@pytest.mark.asyncio -async def test_get_api_version_async_from_dict(): - await test_get_api_version_async(request_type=dict) - - -def test_get_api_version_field_headers(): - client = RegistryClient( - 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 = registry_service.GetApiVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_version), - '__call__') as call: - call.return_value = registry_models.ApiVersion() - client.get_api_version(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_api_version_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.GetApiVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) - await client.get_api_version(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_api_version_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_api_version( - 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_api_version_flattened_error(): - client = RegistryClient( - 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_api_version( - registry_service.GetApiVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_api_version_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_api_version( - 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_api_version_flattened_error_async(): - client = RegistryAsyncClient( - 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_api_version( - registry_service.GetApiVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiVersionRequest, - dict, -]) -def test_create_api_version(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - ) - response = client.create_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -def test_create_api_version_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_version), - '__call__') as call: - client.create_api_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiVersionRequest() - -@pytest.mark.asyncio -async def test_create_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiVersionRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - )) - response = await client.create_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -@pytest.mark.asyncio -async def test_create_api_version_async_from_dict(): - await test_create_api_version_async(request_type=dict) - - -def test_create_api_version_field_headers(): - client = RegistryClient( - 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 = registry_service.CreateApiVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_version), - '__call__') as call: - call.return_value = registry_models.ApiVersion() - client.create_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_api_version_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.CreateApiVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) - await client.create_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_api_version_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_api_version( - parent='parent_value', - api_version=registry_models.ApiVersion(name='name_value'), - api_version_id='api_version_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api_version - mock_val = registry_models.ApiVersion(name='name_value') - assert arg == mock_val - arg = args[0].api_version_id - mock_val = 'api_version_id_value' - assert arg == mock_val - - -def test_create_api_version_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api_version( - registry_service.CreateApiVersionRequest(), - parent='parent_value', - api_version=registry_models.ApiVersion(name='name_value'), - api_version_id='api_version_id_value', - ) - -@pytest.mark.asyncio -async def test_create_api_version_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_api_version( - parent='parent_value', - api_version=registry_models.ApiVersion(name='name_value'), - api_version_id='api_version_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api_version - mock_val = registry_models.ApiVersion(name='name_value') - assert arg == mock_val - arg = args[0].api_version_id - mock_val = 'api_version_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_api_version_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_api_version( - registry_service.CreateApiVersionRequest(), - parent='parent_value', - api_version=registry_models.ApiVersion(name='name_value'), - api_version_id='api_version_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiVersionRequest, - dict, -]) -def test_update_api_version(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - ) - response = client.update_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -def test_update_api_version_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_version), - '__call__') as call: - client.update_api_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiVersionRequest() - -@pytest.mark.asyncio -async def test_update_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiVersionRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - )) - response = await client.update_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiVersionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -@pytest.mark.asyncio -async def test_update_api_version_async_from_dict(): - await test_update_api_version_async(request_type=dict) - - -def test_update_api_version_field_headers(): - client = RegistryClient( - 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 = registry_service.UpdateApiVersionRequest() - - request.api_version.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_version), - '__call__') as call: - call.return_value = registry_models.ApiVersion() - client.update_api_version(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', - 'api_version.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_api_version_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.UpdateApiVersionRequest() - - request.api_version.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) - await client.update_api_version(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', - 'api_version.name=name_value', - ) in kw['metadata'] - - -def test_update_api_version_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_api_version( - api_version=registry_models.ApiVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].api_version - mock_val = registry_models.ApiVersion(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_api_version_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api_version( - registry_service.UpdateApiVersionRequest(), - api_version=registry_models.ApiVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_api_version_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_api_version( - api_version=registry_models.ApiVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].api_version - mock_val = registry_models.ApiVersion(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_api_version_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_api_version( - registry_service.UpdateApiVersionRequest(), - api_version=registry_models.ApiVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiVersionRequest, - dict, -]) -def test_delete_api_version(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiVersionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_version_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_version), - '__call__') as call: - client.delete_api_version() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiVersionRequest() - -@pytest.mark.asyncio -async def test_delete_api_version_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiVersionRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiVersionRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_api_version_async_from_dict(): - await test_delete_api_version_async(request_type=dict) - - -def test_delete_api_version_field_headers(): - client = RegistryClient( - 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 = registry_service.DeleteApiVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_version), - '__call__') as call: - call.return_value = None - client.delete_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_api_version_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.DeleteApiVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_api_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_api_version_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_api_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_api_version_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_version( - registry_service.DeleteApiVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_api_version_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_api_version( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_api_version_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_api_version( - registry_service.DeleteApiVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiSpecsRequest, - dict, -]) -def test_list_api_specs(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiSpecsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_api_specs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiSpecsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiSpecsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_specs_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__') as call: - client.list_api_specs() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiSpecsRequest() - -@pytest.mark.asyncio -async def test_list_api_specs_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiSpecsRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_api_specs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiSpecsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiSpecsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_api_specs_async_from_dict(): - await test_list_api_specs_async(request_type=dict) - - -def test_list_api_specs_field_headers(): - client = RegistryClient( - 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 = registry_service.ListApiSpecsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__') as call: - call.return_value = registry_service.ListApiSpecsResponse() - client.list_api_specs(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_api_specs_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ListApiSpecsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecsResponse()) - await client.list_api_specs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_api_specs_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiSpecsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_api_specs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_api_specs_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_api_specs( - registry_service.ListApiSpecsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_api_specs_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiSpecsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_api_specs( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_api_specs_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_api_specs( - registry_service.ListApiSpecsRequest(), - parent='parent_value', - ) - - -def test_list_api_specs_pager(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_specs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_api_specs(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiSpec) - for i in results) -def test_list_api_specs_pages(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_specs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - pages = list(client.list_api_specs(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_api_specs_async_pager(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_api_specs(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, registry_models.ApiSpec) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_api_specs_async_pages(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_specs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_api_specs(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("request_type", [ - registry_service.GetApiSpecRequest, - dict, -]) -def test_get_api_spec(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - response = client.get_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_get_api_spec_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 = RegistryClient( - 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_api_spec), - '__call__') as call: - client.get_api_spec() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiSpecRequest() - -@pytest.mark.asyncio -async def test_get_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiSpecRequest): - client = RegistryAsyncClient( - 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_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - )) - response = await client.get_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_get_api_spec_async_from_dict(): - await test_get_api_spec_async(request_type=dict) - - -def test_get_api_spec_field_headers(): - client = RegistryClient( - 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 = registry_service.GetApiSpecRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec), - '__call__') as call: - call.return_value = registry_models.ApiSpec() - client.get_api_spec(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_api_spec_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.GetApiSpecRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - await client.get_api_spec(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_api_spec_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_api_spec( - 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_api_spec_flattened_error(): - client = RegistryClient( - 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_api_spec( - registry_service.GetApiSpecRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_api_spec_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_api_spec( - 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_api_spec_flattened_error_async(): - client = RegistryAsyncClient( - 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_api_spec( - registry_service.GetApiSpecRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetApiSpecContentsRequest, - dict, -]) -def test_get_api_spec_contents(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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_api_spec_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.get_api_spec_contents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiSpecContentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_get_api_spec_contents_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 = RegistryClient( - 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_api_spec_contents), - '__call__') as call: - client.get_api_spec_contents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiSpecContentsRequest() - -@pytest.mark.asyncio -async def test_get_api_spec_contents_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiSpecContentsRequest): - client = RegistryAsyncClient( - 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_api_spec_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.get_api_spec_contents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiSpecContentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_get_api_spec_contents_async_from_dict(): - await test_get_api_spec_contents_async(request_type=dict) - - -def test_get_api_spec_contents_field_headers(): - client = RegistryClient( - 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 = registry_service.GetApiSpecContentsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec_contents), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.get_api_spec_contents(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_api_spec_contents_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.GetApiSpecContentsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec_contents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.get_api_spec_contents(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_api_spec_contents_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_api_spec_contents( - 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_api_spec_contents_flattened_error(): - client = RegistryClient( - 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_api_spec_contents( - registry_service.GetApiSpecContentsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_api_spec_contents_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_spec_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_api_spec_contents( - 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_api_spec_contents_flattened_error_async(): - client = RegistryAsyncClient( - 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_api_spec_contents( - registry_service.GetApiSpecContentsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiSpecRequest, - dict, -]) -def test_create_api_spec(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - response = client.create_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_create_api_spec_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_spec), - '__call__') as call: - client.create_api_spec() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiSpecRequest() - -@pytest.mark.asyncio -async def test_create_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiSpecRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - )) - response = await client.create_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_create_api_spec_async_from_dict(): - await test_create_api_spec_async(request_type=dict) - - -def test_create_api_spec_field_headers(): - client = RegistryClient( - 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 = registry_service.CreateApiSpecRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_spec), - '__call__') as call: - call.return_value = registry_models.ApiSpec() - client.create_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_api_spec_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.CreateApiSpecRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_spec), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - await client.create_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_api_spec_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_api_spec( - parent='parent_value', - api_spec=registry_models.ApiSpec(name='name_value'), - api_spec_id='api_spec_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api_spec - mock_val = registry_models.ApiSpec(name='name_value') - assert arg == mock_val - arg = args[0].api_spec_id - mock_val = 'api_spec_id_value' - assert arg == mock_val - - -def test_create_api_spec_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api_spec( - registry_service.CreateApiSpecRequest(), - parent='parent_value', - api_spec=registry_models.ApiSpec(name='name_value'), - api_spec_id='api_spec_id_value', - ) - -@pytest.mark.asyncio -async def test_create_api_spec_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_api_spec( - parent='parent_value', - api_spec=registry_models.ApiSpec(name='name_value'), - api_spec_id='api_spec_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api_spec - mock_val = registry_models.ApiSpec(name='name_value') - assert arg == mock_val - arg = args[0].api_spec_id - mock_val = 'api_spec_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_api_spec_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_api_spec( - registry_service.CreateApiSpecRequest(), - parent='parent_value', - api_spec=registry_models.ApiSpec(name='name_value'), - api_spec_id='api_spec_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiSpecRequest, - dict, -]) -def test_update_api_spec(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - response = client.update_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_update_api_spec_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_spec), - '__call__') as call: - client.update_api_spec() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiSpecRequest() - -@pytest.mark.asyncio -async def test_update_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiSpecRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - )) - response = await client.update_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_update_api_spec_async_from_dict(): - await test_update_api_spec_async(request_type=dict) - - -def test_update_api_spec_field_headers(): - client = RegistryClient( - 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 = registry_service.UpdateApiSpecRequest() - - request.api_spec.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_spec), - '__call__') as call: - call.return_value = registry_models.ApiSpec() - client.update_api_spec(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', - 'api_spec.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_api_spec_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.UpdateApiSpecRequest() - - request.api_spec.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_spec), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - await client.update_api_spec(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', - 'api_spec.name=name_value', - ) in kw['metadata'] - - -def test_update_api_spec_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_api_spec( - api_spec=registry_models.ApiSpec(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].api_spec - mock_val = registry_models.ApiSpec(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_api_spec_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api_spec( - registry_service.UpdateApiSpecRequest(), - api_spec=registry_models.ApiSpec(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_api_spec_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_api_spec( - api_spec=registry_models.ApiSpec(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].api_spec - mock_val = registry_models.ApiSpec(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_api_spec_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_api_spec( - registry_service.UpdateApiSpecRequest(), - api_spec=registry_models.ApiSpec(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiSpecRequest, - dict, -]) -def test_delete_api_spec(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiSpecRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_spec_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec), - '__call__') as call: - client.delete_api_spec() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiSpecRequest() - -@pytest.mark.asyncio -async def test_delete_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiSpecRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiSpecRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_api_spec_async_from_dict(): - await test_delete_api_spec_async(request_type=dict) - - -def test_delete_api_spec_field_headers(): - client = RegistryClient( - 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 = registry_service.DeleteApiSpecRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec), - '__call__') as call: - call.return_value = None - client.delete_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_api_spec_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.DeleteApiSpecRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_api_spec_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_api_spec( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_api_spec_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_spec( - registry_service.DeleteApiSpecRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_api_spec_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_api_spec( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_api_spec_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_api_spec( - registry_service.DeleteApiSpecRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.TagApiSpecRevisionRequest, - dict, -]) -def test_tag_api_spec_revision(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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.tag_api_spec_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - response = client.tag_api_spec_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.TagApiSpecRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_tag_api_spec_revision_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 = RegistryClient( - 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.tag_api_spec_revision), - '__call__') as call: - client.tag_api_spec_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.TagApiSpecRevisionRequest() - -@pytest.mark.asyncio -async def test_tag_api_spec_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.TagApiSpecRevisionRequest): - client = RegistryAsyncClient( - 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.tag_api_spec_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - )) - response = await client.tag_api_spec_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.TagApiSpecRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_tag_api_spec_revision_async_from_dict(): - await test_tag_api_spec_revision_async(request_type=dict) - - -def test_tag_api_spec_revision_field_headers(): - client = RegistryClient( - 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 = registry_service.TagApiSpecRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tag_api_spec_revision), - '__call__') as call: - call.return_value = registry_models.ApiSpec() - client.tag_api_spec_revision(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_tag_api_spec_revision_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.TagApiSpecRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tag_api_spec_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - await client.tag_api_spec_revision(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'] - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiSpecRevisionsRequest, - dict, -]) -def test_list_api_spec_revisions(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_spec_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiSpecRevisionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_api_spec_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiSpecRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiSpecRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_spec_revisions_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_spec_revisions), - '__call__') as call: - client.list_api_spec_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiSpecRevisionsRequest() - -@pytest.mark.asyncio -async def test_list_api_spec_revisions_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiSpecRevisionsRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_spec_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecRevisionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_api_spec_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiSpecRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiSpecRevisionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_api_spec_revisions_async_from_dict(): - await test_list_api_spec_revisions_async(request_type=dict) - - -def test_list_api_spec_revisions_field_headers(): - client = RegistryClient( - 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 = registry_service.ListApiSpecRevisionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_spec_revisions), - '__call__') as call: - call.return_value = registry_service.ListApiSpecRevisionsResponse() - client.list_api_spec_revisions(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_list_api_spec_revisions_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ListApiSpecRevisionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_spec_revisions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiSpecRevisionsResponse()) - await client.list_api_spec_revisions(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_list_api_spec_revisions_pager(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_spec_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.list_api_spec_revisions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiSpec) - for i in results) -def test_list_api_spec_revisions_pages(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_spec_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - pages = list(client.list_api_spec_revisions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_api_spec_revisions_async_pager(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_spec_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_api_spec_revisions(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, registry_models.ApiSpec) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_api_spec_revisions_async_pages(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_spec_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_api_spec_revisions(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("request_type", [ - registry_service.RollbackApiSpecRequest, - dict, -]) -def test_rollback_api_spec(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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.rollback_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - response = client.rollback_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.RollbackApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_rollback_api_spec_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 = RegistryClient( - 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.rollback_api_spec), - '__call__') as call: - client.rollback_api_spec() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.RollbackApiSpecRequest() - -@pytest.mark.asyncio -async def test_rollback_api_spec_async(transport: str = 'grpc_asyncio', request_type=registry_service.RollbackApiSpecRequest): - client = RegistryAsyncClient( - 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.rollback_api_spec), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - )) - response = await client.rollback_api_spec(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.RollbackApiSpecRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_rollback_api_spec_async_from_dict(): - await test_rollback_api_spec_async(request_type=dict) - - -def test_rollback_api_spec_field_headers(): - client = RegistryClient( - 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 = registry_service.RollbackApiSpecRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_api_spec), - '__call__') as call: - call.return_value = registry_models.ApiSpec() - client.rollback_api_spec(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_rollback_api_spec_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.RollbackApiSpecRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_api_spec), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - await client.rollback_api_spec(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'] - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiSpecRevisionRequest, - dict, -]) -def test_delete_api_spec_revision(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - response = client.delete_api_spec_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiSpecRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_delete_api_spec_revision_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec_revision), - '__call__') as call: - client.delete_api_spec_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiSpecRevisionRequest() - -@pytest.mark.asyncio -async def test_delete_api_spec_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiSpecRevisionRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - )) - response = await client.delete_api_spec_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiSpecRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_delete_api_spec_revision_async_from_dict(): - await test_delete_api_spec_revision_async(request_type=dict) - - -def test_delete_api_spec_revision_field_headers(): - client = RegistryClient( - 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 = registry_service.DeleteApiSpecRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec_revision), - '__call__') as call: - call.return_value = registry_models.ApiSpec() - client.delete_api_spec_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_api_spec_revision_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.DeleteApiSpecRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - await client.delete_api_spec_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_api_spec_revision_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_api_spec_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_api_spec_revision_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_spec_revision( - registry_service.DeleteApiSpecRevisionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_api_spec_revision_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_spec_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiSpec() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiSpec()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_api_spec_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_api_spec_revision_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_api_spec_revision( - registry_service.DeleteApiSpecRevisionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiDeploymentsRequest, - dict, -]) -def test_list_api_deployments(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiDeploymentsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_api_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiDeploymentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiDeploymentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_deployments_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__') as call: - client.list_api_deployments() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiDeploymentsRequest() - -@pytest.mark.asyncio -async def test_list_api_deployments_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiDeploymentsRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_api_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiDeploymentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiDeploymentsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_api_deployments_async_from_dict(): - await test_list_api_deployments_async(request_type=dict) - - -def test_list_api_deployments_field_headers(): - client = RegistryClient( - 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 = registry_service.ListApiDeploymentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__') as call: - call.return_value = registry_service.ListApiDeploymentsResponse() - client.list_api_deployments(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_api_deployments_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ListApiDeploymentsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentsResponse()) - await client.list_api_deployments(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_api_deployments_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiDeploymentsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_api_deployments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_api_deployments_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_api_deployments( - registry_service.ListApiDeploymentsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_api_deployments_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiDeploymentsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_api_deployments( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_api_deployments_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_api_deployments( - registry_service.ListApiDeploymentsRequest(), - parent='parent_value', - ) - - -def test_list_api_deployments_pager(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_deployments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_api_deployments(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiDeployment) - for i in results) -def test_list_api_deployments_pages(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_deployments), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_api_deployments(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_api_deployments_async_pager(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_api_deployments(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, registry_models.ApiDeployment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_api_deployments_async_pages(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployments), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_api_deployments(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("request_type", [ - registry_service.GetApiDeploymentRequest, - dict, -]) -def test_get_api_deployment(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - response = client.get_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_get_api_deployment_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 = RegistryClient( - 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_api_deployment), - '__call__') as call: - client.get_api_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiDeploymentRequest() - -@pytest.mark.asyncio -async def test_get_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetApiDeploymentRequest): - client = RegistryAsyncClient( - 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_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - )) - response = await client.get_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -@pytest.mark.asyncio -async def test_get_api_deployment_async_from_dict(): - await test_get_api_deployment_async(request_type=dict) - - -def test_get_api_deployment_field_headers(): - client = RegistryClient( - 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 = registry_service.GetApiDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_deployment), - '__call__') as call: - call.return_value = registry_models.ApiDeployment() - client.get_api_deployment(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_api_deployment_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.GetApiDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - await client.get_api_deployment(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_api_deployment_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_api_deployment( - 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_api_deployment_flattened_error(): - client = RegistryClient( - 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_api_deployment( - registry_service.GetApiDeploymentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_api_deployment_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_api_deployment( - 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_api_deployment_flattened_error_async(): - client = RegistryAsyncClient( - 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_api_deployment( - registry_service.GetApiDeploymentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiDeploymentRequest, - dict, -]) -def test_create_api_deployment(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - response = client.create_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_create_api_deployment_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_deployment), - '__call__') as call: - client.create_api_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiDeploymentRequest() - -@pytest.mark.asyncio -async def test_create_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateApiDeploymentRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - )) - response = await client.create_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -@pytest.mark.asyncio -async def test_create_api_deployment_async_from_dict(): - await test_create_api_deployment_async(request_type=dict) - - -def test_create_api_deployment_field_headers(): - client = RegistryClient( - 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 = registry_service.CreateApiDeploymentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_deployment), - '__call__') as call: - call.return_value = registry_models.ApiDeployment() - client.create_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_api_deployment_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.CreateApiDeploymentRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - await client.create_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_api_deployment_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_api_deployment( - parent='parent_value', - api_deployment=registry_models.ApiDeployment(name='name_value'), - api_deployment_id='api_deployment_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api_deployment - mock_val = registry_models.ApiDeployment(name='name_value') - assert arg == mock_val - arg = args[0].api_deployment_id - mock_val = 'api_deployment_id_value' - assert arg == mock_val - - -def test_create_api_deployment_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api_deployment( - registry_service.CreateApiDeploymentRequest(), - parent='parent_value', - api_deployment=registry_models.ApiDeployment(name='name_value'), - api_deployment_id='api_deployment_id_value', - ) - -@pytest.mark.asyncio -async def test_create_api_deployment_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_api_deployment( - parent='parent_value', - api_deployment=registry_models.ApiDeployment(name='name_value'), - api_deployment_id='api_deployment_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].api_deployment - mock_val = registry_models.ApiDeployment(name='name_value') - assert arg == mock_val - arg = args[0].api_deployment_id - mock_val = 'api_deployment_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_api_deployment_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_api_deployment( - registry_service.CreateApiDeploymentRequest(), - parent='parent_value', - api_deployment=registry_models.ApiDeployment(name='name_value'), - api_deployment_id='api_deployment_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiDeploymentRequest, - dict, -]) -def test_update_api_deployment(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - response = client.update_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_update_api_deployment_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_deployment), - '__call__') as call: - client.update_api_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiDeploymentRequest() - -@pytest.mark.asyncio -async def test_update_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.UpdateApiDeploymentRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - )) - response = await client.update_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.UpdateApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -@pytest.mark.asyncio -async def test_update_api_deployment_async_from_dict(): - await test_update_api_deployment_async(request_type=dict) - - -def test_update_api_deployment_field_headers(): - client = RegistryClient( - 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 = registry_service.UpdateApiDeploymentRequest() - - request.api_deployment.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_deployment), - '__call__') as call: - call.return_value = registry_models.ApiDeployment() - client.update_api_deployment(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', - 'api_deployment.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_api_deployment_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.UpdateApiDeploymentRequest() - - request.api_deployment.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - await client.update_api_deployment(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', - 'api_deployment.name=name_value', - ) in kw['metadata'] - - -def test_update_api_deployment_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_api_deployment( - api_deployment=registry_models.ApiDeployment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].api_deployment - mock_val = registry_models.ApiDeployment(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - - -def test_update_api_deployment_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api_deployment( - registry_service.UpdateApiDeploymentRequest(), - api_deployment=registry_models.ApiDeployment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_api_deployment_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_api_deployment( - api_deployment=registry_models.ApiDeployment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].api_deployment - mock_val = registry_models.ApiDeployment(name='name_value') - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=['paths_value']) - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_api_deployment_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_api_deployment( - registry_service.UpdateApiDeploymentRequest(), - api_deployment=registry_models.ApiDeployment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiDeploymentRequest, - dict, -]) -def test_delete_api_deployment(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_deployment_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment), - '__call__') as call: - client.delete_api_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiDeploymentRequest() - -@pytest.mark.asyncio -async def test_delete_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiDeploymentRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_api_deployment_async_from_dict(): - await test_delete_api_deployment_async(request_type=dict) - - -def test_delete_api_deployment_field_headers(): - client = RegistryClient( - 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 = registry_service.DeleteApiDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment), - '__call__') as call: - call.return_value = None - client.delete_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_api_deployment_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.DeleteApiDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_api_deployment_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_api_deployment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_api_deployment_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_deployment( - registry_service.DeleteApiDeploymentRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_api_deployment_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_api_deployment( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_api_deployment_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_api_deployment( - registry_service.DeleteApiDeploymentRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.TagApiDeploymentRevisionRequest, - dict, -]) -def test_tag_api_deployment_revision(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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.tag_api_deployment_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - response = client.tag_api_deployment_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.TagApiDeploymentRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_tag_api_deployment_revision_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 = RegistryClient( - 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.tag_api_deployment_revision), - '__call__') as call: - client.tag_api_deployment_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.TagApiDeploymentRevisionRequest() - -@pytest.mark.asyncio -async def test_tag_api_deployment_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.TagApiDeploymentRevisionRequest): - client = RegistryAsyncClient( - 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.tag_api_deployment_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - )) - response = await client.tag_api_deployment_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.TagApiDeploymentRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -@pytest.mark.asyncio -async def test_tag_api_deployment_revision_async_from_dict(): - await test_tag_api_deployment_revision_async(request_type=dict) - - -def test_tag_api_deployment_revision_field_headers(): - client = RegistryClient( - 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 = registry_service.TagApiDeploymentRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tag_api_deployment_revision), - '__call__') as call: - call.return_value = registry_models.ApiDeployment() - client.tag_api_deployment_revision(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_tag_api_deployment_revision_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.TagApiDeploymentRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.tag_api_deployment_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - await client.tag_api_deployment_revision(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'] - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiDeploymentRevisionsRequest, - dict, -]) -def test_list_api_deployment_revisions(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployment_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListApiDeploymentRevisionsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_api_deployment_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiDeploymentRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiDeploymentRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_deployment_revisions_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployment_revisions), - '__call__') as call: - client.list_api_deployment_revisions() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiDeploymentRevisionsRequest() - -@pytest.mark.asyncio -async def test_list_api_deployment_revisions_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListApiDeploymentRevisionsRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployment_revisions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentRevisionsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_api_deployment_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListApiDeploymentRevisionsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiDeploymentRevisionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_api_deployment_revisions_async_from_dict(): - await test_list_api_deployment_revisions_async(request_type=dict) - - -def test_list_api_deployment_revisions_field_headers(): - client = RegistryClient( - 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 = registry_service.ListApiDeploymentRevisionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployment_revisions), - '__call__') as call: - call.return_value = registry_service.ListApiDeploymentRevisionsResponse() - client.list_api_deployment_revisions(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_list_api_deployment_revisions_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ListApiDeploymentRevisionsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployment_revisions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListApiDeploymentRevisionsResponse()) - await client.list_api_deployment_revisions(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_list_api_deployment_revisions_pager(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_deployment_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('name', ''), - )), - ) - pager = client.list_api_deployment_revisions(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiDeployment) - for i in results) -def test_list_api_deployment_revisions_pages(transport_name: str = "grpc"): - client = RegistryClient( - 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_api_deployment_revisions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - pages = list(client.list_api_deployment_revisions(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_api_deployment_revisions_async_pager(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployment_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_api_deployment_revisions(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, registry_models.ApiDeployment) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_api_deployment_revisions_async_pages(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_api_deployment_revisions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_api_deployment_revisions(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("request_type", [ - registry_service.RollbackApiDeploymentRequest, - dict, -]) -def test_rollback_api_deployment(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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.rollback_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - response = client.rollback_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.RollbackApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_rollback_api_deployment_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 = RegistryClient( - 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.rollback_api_deployment), - '__call__') as call: - client.rollback_api_deployment() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.RollbackApiDeploymentRequest() - -@pytest.mark.asyncio -async def test_rollback_api_deployment_async(transport: str = 'grpc_asyncio', request_type=registry_service.RollbackApiDeploymentRequest): - client = RegistryAsyncClient( - 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.rollback_api_deployment), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - )) - response = await client.rollback_api_deployment(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.RollbackApiDeploymentRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -@pytest.mark.asyncio -async def test_rollback_api_deployment_async_from_dict(): - await test_rollback_api_deployment_async(request_type=dict) - - -def test_rollback_api_deployment_field_headers(): - client = RegistryClient( - 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 = registry_service.RollbackApiDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_api_deployment), - '__call__') as call: - call.return_value = registry_models.ApiDeployment() - client.rollback_api_deployment(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_rollback_api_deployment_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.RollbackApiDeploymentRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.rollback_api_deployment), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - await client.rollback_api_deployment(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'] - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiDeploymentRevisionRequest, - dict, -]) -def test_delete_api_deployment_revision(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - response = client.delete_api_deployment_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiDeploymentRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_delete_api_deployment_revision_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment_revision), - '__call__') as call: - client.delete_api_deployment_revision() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiDeploymentRevisionRequest() - -@pytest.mark.asyncio -async def test_delete_api_deployment_revision_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteApiDeploymentRevisionRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - )) - response = await client.delete_api_deployment_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteApiDeploymentRevisionRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -@pytest.mark.asyncio -async def test_delete_api_deployment_revision_async_from_dict(): - await test_delete_api_deployment_revision_async(request_type=dict) - - -def test_delete_api_deployment_revision_field_headers(): - client = RegistryClient( - 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 = registry_service.DeleteApiDeploymentRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment_revision), - '__call__') as call: - call.return_value = registry_models.ApiDeployment() - client.delete_api_deployment_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_api_deployment_revision_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.DeleteApiDeploymentRevisionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment_revision), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - await client.delete_api_deployment_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_api_deployment_revision_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_api_deployment_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_api_deployment_revision_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_deployment_revision( - registry_service.DeleteApiDeploymentRevisionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_api_deployment_revision_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_api_deployment_revision), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.ApiDeployment() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.ApiDeployment()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_api_deployment_revision( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_api_deployment_revision_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_api_deployment_revision( - registry_service.DeleteApiDeploymentRevisionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListArtifactsRequest, - dict, -]) -def test_list_artifacts(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListArtifactsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_artifacts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListArtifactsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListArtifactsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_artifacts_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__') as call: - client.list_artifacts() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListArtifactsRequest() - -@pytest.mark.asyncio -async def test_list_artifacts_async(transport: str = 'grpc_asyncio', request_type=registry_service.ListArtifactsRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListArtifactsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_artifacts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ListArtifactsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListArtifactsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_artifacts_async_from_dict(): - await test_list_artifacts_async(request_type=dict) - - -def test_list_artifacts_field_headers(): - client = RegistryClient( - 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 = registry_service.ListArtifactsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__') as call: - call.return_value = registry_service.ListArtifactsResponse() - client.list_artifacts(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_artifacts_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ListArtifactsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListArtifactsResponse()) - await client.list_artifacts(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_artifacts_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListArtifactsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_artifacts( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - - -def test_list_artifacts_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_artifacts( - registry_service.ListArtifactsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_artifacts_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_service.ListArtifactsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_service.ListArtifactsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_artifacts( - parent='parent_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_list_artifacts_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_artifacts( - registry_service.ListArtifactsRequest(), - parent='parent_value', - ) - - -def test_list_artifacts_pager(transport_name: str = "grpc"): - client = RegistryClient( - 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_artifacts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - registry_models.Artifact(), - ], - next_page_token='abc', - ), - registry_service.ListArtifactsResponse( - artifacts=[], - next_page_token='def', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - ], - next_page_token='ghi', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_artifacts(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.Artifact) - for i in results) -def test_list_artifacts_pages(transport_name: str = "grpc"): - client = RegistryClient( - 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_artifacts), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - registry_models.Artifact(), - ], - next_page_token='abc', - ), - registry_service.ListArtifactsResponse( - artifacts=[], - next_page_token='def', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - ], - next_page_token='ghi', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - ], - ), - RuntimeError, - ) - pages = list(client.list_artifacts(request={}).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_artifacts_async_pager(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - registry_models.Artifact(), - ], - next_page_token='abc', - ), - registry_service.ListArtifactsResponse( - artifacts=[], - next_page_token='def', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - ], - next_page_token='ghi', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_artifacts(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, registry_models.Artifact) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_artifacts_async_pages(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_artifacts), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - registry_models.Artifact(), - ], - next_page_token='abc', - ), - registry_service.ListArtifactsResponse( - artifacts=[], - next_page_token='def', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - ], - next_page_token='ghi', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_artifacts(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("request_type", [ - registry_service.GetArtifactRequest, - dict, -]) -def test_get_artifact(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - ) - response = client.get_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetArtifactRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -def test_get_artifact_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 = RegistryClient( - 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_artifact), - '__call__') as call: - client.get_artifact() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetArtifactRequest() - -@pytest.mark.asyncio -async def test_get_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetArtifactRequest): - client = RegistryAsyncClient( - 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_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - )) - response = await client.get_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetArtifactRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_get_artifact_async_from_dict(): - await test_get_artifact_async(request_type=dict) - - -def test_get_artifact_field_headers(): - client = RegistryClient( - 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 = registry_service.GetArtifactRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact), - '__call__') as call: - call.return_value = registry_models.Artifact() - client.get_artifact(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_artifact_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.GetArtifactRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) - await client.get_artifact(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_artifact_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_artifact( - 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_artifact_flattened_error(): - client = RegistryClient( - 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_artifact( - registry_service.GetArtifactRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_artifact_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_artifact( - 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_artifact_flattened_error_async(): - client = RegistryAsyncClient( - 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_artifact( - registry_service.GetArtifactRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetArtifactContentsRequest, - dict, -]) -def test_get_artifact_contents(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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_artifact_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - response = client.get_artifact_contents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetArtifactContentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_get_artifact_contents_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 = RegistryClient( - 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_artifact_contents), - '__call__') as call: - client.get_artifact_contents() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetArtifactContentsRequest() - -@pytest.mark.asyncio -async def test_get_artifact_contents_async(transport: str = 'grpc_asyncio', request_type=registry_service.GetArtifactContentsRequest): - client = RegistryAsyncClient( - 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_artifact_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - )) - response = await client.get_artifact_contents(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.GetArtifactContentsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_get_artifact_contents_async_from_dict(): - await test_get_artifact_contents_async(request_type=dict) - - -def test_get_artifact_contents_field_headers(): - client = RegistryClient( - 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 = registry_service.GetArtifactContentsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact_contents), - '__call__') as call: - call.return_value = httpbody_pb2.HttpBody() - client.get_artifact_contents(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_artifact_contents_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.GetArtifactContentsRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact_contents), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - await client.get_artifact_contents(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_artifact_contents_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_artifact_contents( - 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_artifact_contents_flattened_error(): - client = RegistryClient( - 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_artifact_contents( - registry_service.GetArtifactContentsRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_artifact_contents_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_artifact_contents), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = httpbody_pb2.HttpBody() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(httpbody_pb2.HttpBody()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_artifact_contents( - 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_artifact_contents_flattened_error_async(): - client = RegistryAsyncClient( - 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_artifact_contents( - registry_service.GetArtifactContentsRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateArtifactRequest, - dict, -]) -def test_create_artifact(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - ) - response = client.create_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateArtifactRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -def test_create_artifact_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_artifact), - '__call__') as call: - client.create_artifact() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateArtifactRequest() - -@pytest.mark.asyncio -async def test_create_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.CreateArtifactRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - )) - response = await client.create_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.CreateArtifactRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_create_artifact_async_from_dict(): - await test_create_artifact_async(request_type=dict) - - -def test_create_artifact_field_headers(): - client = RegistryClient( - 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 = registry_service.CreateArtifactRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_artifact), - '__call__') as call: - call.return_value = registry_models.Artifact() - client.create_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_create_artifact_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.CreateArtifactRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_artifact), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) - await client.create_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_create_artifact_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_artifact( - parent='parent_value', - artifact=registry_models.Artifact(name='name_value'), - artifact_id='artifact_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].artifact - mock_val = registry_models.Artifact(name='name_value') - assert arg == mock_val - arg = args[0].artifact_id - mock_val = 'artifact_id_value' - assert arg == mock_val - - -def test_create_artifact_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_artifact( - registry_service.CreateArtifactRequest(), - parent='parent_value', - artifact=registry_models.Artifact(name='name_value'), - artifact_id='artifact_id_value', - ) - -@pytest.mark.asyncio -async def test_create_artifact_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_artifact( - parent='parent_value', - artifact=registry_models.Artifact(name='name_value'), - artifact_id='artifact_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].artifact - mock_val = registry_models.Artifact(name='name_value') - assert arg == mock_val - arg = args[0].artifact_id - mock_val = 'artifact_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_artifact_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_artifact( - registry_service.CreateArtifactRequest(), - parent='parent_value', - artifact=registry_models.Artifact(name='name_value'), - artifact_id='artifact_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ReplaceArtifactRequest, - dict, -]) -def test_replace_artifact(request_type, transport: str = 'grpc'): - client = RegistryClient( - 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.replace_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - ) - response = client.replace_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ReplaceArtifactRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -def test_replace_artifact_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 = RegistryClient( - 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.replace_artifact), - '__call__') as call: - client.replace_artifact() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ReplaceArtifactRequest() - -@pytest.mark.asyncio -async def test_replace_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.ReplaceArtifactRequest): - client = RegistryAsyncClient( - 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.replace_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - )) - response = await client.replace_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.ReplaceArtifactRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -@pytest.mark.asyncio -async def test_replace_artifact_async_from_dict(): - await test_replace_artifact_async(request_type=dict) - - -def test_replace_artifact_field_headers(): - client = RegistryClient( - 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 = registry_service.ReplaceArtifactRequest() - - request.artifact.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_artifact), - '__call__') as call: - call.return_value = registry_models.Artifact() - client.replace_artifact(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', - 'artifact.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_replace_artifact_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.ReplaceArtifactRequest() - - request.artifact.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_artifact), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) - await client.replace_artifact(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', - 'artifact.name=name_value', - ) in kw['metadata'] - - -def test_replace_artifact_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.replace_artifact( - artifact=registry_models.Artifact(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].artifact - mock_val = registry_models.Artifact(name='name_value') - assert arg == mock_val - - -def test_replace_artifact_flattened_error(): - client = RegistryClient( - 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.replace_artifact( - registry_service.ReplaceArtifactRequest(), - artifact=registry_models.Artifact(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_replace_artifact_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.replace_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = registry_models.Artifact() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(registry_models.Artifact()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.replace_artifact( - artifact=registry_models.Artifact(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].artifact - mock_val = registry_models.Artifact(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_replace_artifact_flattened_error_async(): - client = RegistryAsyncClient( - 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.replace_artifact( - registry_service.ReplaceArtifactRequest(), - artifact=registry_models.Artifact(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteArtifactRequest, - dict, -]) -def test_delete_artifact(request_type, transport: str = 'grpc'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteArtifactRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_artifact_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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_artifact), - '__call__') as call: - client.delete_artifact() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteArtifactRequest() - -@pytest.mark.asyncio -async def test_delete_artifact_async(transport: str = 'grpc_asyncio', request_type=registry_service.DeleteArtifactRequest): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == registry_service.DeleteArtifactRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_artifact_async_from_dict(): - await test_delete_artifact_async(request_type=dict) - - -def test_delete_artifact_field_headers(): - client = RegistryClient( - 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 = registry_service.DeleteArtifactRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_artifact), - '__call__') as call: - call.return_value = None - client.delete_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_delete_artifact_field_headers_async(): - client = RegistryAsyncClient( - 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 = registry_service.DeleteArtifactRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_artifact), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_artifact(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_delete_artifact_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_artifact( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_delete_artifact_flattened_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_artifact( - registry_service.DeleteArtifactRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_artifact_flattened_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_artifact), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_artifact( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_delete_artifact_flattened_error_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_artifact( - registry_service.DeleteArtifactRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApisRequest, - dict, -]) -def test_list_apis_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApisResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApisResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_apis(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApisPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_apis_rest_required_fields(request_type=registry_service.ListApisRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_apis._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_apis._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApisResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_service.ListApisResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_apis(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_apis_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_apis._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_apis_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_list_apis") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_list_apis") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ListApisRequest.pb(registry_service.ListApisRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_service.ListApisResponse.to_json(registry_service.ListApisResponse()) - - request = registry_service.ListApisRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_service.ListApisResponse() - - client.list_apis(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_apis_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApisRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_apis(request) - - -def test_list_apis_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApisResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApisResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_apis(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/apis" % client.transport._host, args[1]) - - -def test_list_apis_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_apis( - registry_service.ListApisRequest(), - parent='parent_value', - ) - - -def test_list_apis_rest_pager(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - registry_models.Api(), - ], - next_page_token='abc', - ), - registry_service.ListApisResponse( - apis=[], - next_page_token='def', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - ], - next_page_token='ghi', - ), - registry_service.ListApisResponse( - apis=[ - registry_models.Api(), - registry_models.Api(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(registry_service.ListApisResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_apis(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.Api) - for i in results) - - pages = list(client.list_apis(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetApiRequest, - dict, -]) -def test_get_api_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_api(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -def test_get_api_rest_required_fields(request_type=registry_service.GetApiRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.Api() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_api(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_api_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_api._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_api_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_get_api") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.GetApiRequest.pb(registry_service.GetApiRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.Api.to_json(registry_models.Api()) - - request = registry_service.GetApiRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.Api() - - client.get_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_api(request) - - -def test_get_api_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Api() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_api(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*}" % client.transport._host, args[1]) - - -def test_get_api_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_api( - registry_service.GetApiRequest(), - name='name_value', - ) - - -def test_get_api_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiRequest, - dict, -]) -def test_create_api_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["api"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_api(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -def test_create_api_rest_required_fields(request_type=registry_service.CreateApiRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["api_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "apiId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "apiId" in jsonified_request - assert jsonified_request["apiId"] == request_init["api_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["apiId"] = 'api_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("api_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "apiId" in jsonified_request - assert jsonified_request["apiId"] == 'api_id_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.Api() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_api(request) - - expected_params = [ - ( - "apiId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_api_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_api._get_unset_required_fields({}) - assert set(unset_fields) == (set(("apiId", )) & set(("parent", "api", "apiId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_api_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_create_api") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.CreateApiRequest.pb(registry_service.CreateApiRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.Api.to_json(registry_models.Api()) - - request = registry_service.CreateApiRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.Api() - - client.create_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["api"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_api(request) - - -def test_create_api_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Api() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - api=registry_models.Api(name='name_value'), - api_id='api_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_api(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/apis" % client.transport._host, args[1]) - - -def test_create_api_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api( - registry_service.CreateApiRequest(), - parent='parent_value', - api=registry_models.Api(name='name_value'), - api_id='api_id_value', - ) - - -def test_create_api_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiRequest, - dict, -]) -def test_update_api_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'api': {'name': 'projects/sample1/locations/sample2/apis/sample3'}} - request_init["api"] = {'name': 'projects/sample1/locations/sample2/apis/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Api( - name='name_value', - display_name='display_name_value', - description='description_value', - availability='availability_value', - recommended_version='recommended_version_value', - recommended_deployment='recommended_deployment_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_api(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Api) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.availability == 'availability_value' - assert response.recommended_version == 'recommended_version_value' - assert response.recommended_deployment == 'recommended_deployment_value' - - -def test_update_api_rest_required_fields(request_type=registry_service.UpdateApiRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.Api() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_api(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_api_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_api._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("api", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_api_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_update_api") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.UpdateApiRequest.pb(registry_service.UpdateApiRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.Api.to_json(registry_models.Api()) - - request = registry_service.UpdateApiRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.Api() - - client.update_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'api': {'name': 'projects/sample1/locations/sample2/apis/sample3'}} - request_init["api"] = {'name': 'projects/sample1/locations/sample2/apis/sample3', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'availability': 'availability_value', 'recommended_version': 'recommended_version_value', 'recommended_deployment': 'recommended_deployment_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_api(request) - - -def test_update_api_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Api() - - # get arguments that satisfy an http rule for this method - sample_request = {'api': {'name': 'projects/sample1/locations/sample2/apis/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - api=registry_models.Api(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Api.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_api(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{api.name=projects/*/locations/*/apis/*}" % client.transport._host, args[1]) - - -def test_update_api_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api( - registry_service.UpdateApiRequest(), - api=registry_models.Api(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_api_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiRequest, - dict, -]) -def test_delete_api_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_api(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_rest_required_fields(request_type=registry_service.DeleteApiRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_api(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_api_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_api._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_api_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api") as pre: - pre.assert_not_called() - pb_message = registry_service.DeleteApiRequest.pb(registry_service.DeleteApiRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = registry_service.DeleteApiRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_api(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_api_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_api(request) - - -def test_delete_api_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_api(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*}" % client.transport._host, args[1]) - - -def test_delete_api_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api( - registry_service.DeleteApiRequest(), - name='name_value', - ) - - -def test_delete_api_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiVersionsRequest, - dict, -]) -def test_list_api_versions_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiVersionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_api_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiVersionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_versions_rest_required_fields(request_type=registry_service.ListApiVersionsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_service.ListApiVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_api_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_api_versions_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_api_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_api_versions_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_versions") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ListApiVersionsRequest.pb(registry_service.ListApiVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_service.ListApiVersionsResponse.to_json(registry_service.ListApiVersionsResponse()) - - request = registry_service.ListApiVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_service.ListApiVersionsResponse() - - client.list_api_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_api_versions_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiVersionsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_api_versions(request) - - -def test_list_api_versions_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiVersionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_api_versions(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/versions" % client.transport._host, args[1]) - - -def test_list_api_versions_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_api_versions( - registry_service.ListApiVersionsRequest(), - parent='parent_value', - ) - - -def test_list_api_versions_rest_pager(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - next_page_token='abc', - ), - registry_service.ListApiVersionsResponse( - api_versions=[], - next_page_token='def', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - ], - next_page_token='ghi', - ), - registry_service.ListApiVersionsResponse( - api_versions=[ - registry_models.ApiVersion(), - registry_models.ApiVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(registry_service.ListApiVersionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - - pager = client.list_api_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiVersion) - for i in results) - - pages = list(client.list_api_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetApiVersionRequest, - dict, -]) -def test_get_api_version_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_api_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -def test_get_api_version_rest_required_fields(request_type=registry_service.GetApiVersionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_api_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_api_version_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_api_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_api_version_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_version") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.GetApiVersionRequest.pb(registry_service.GetApiVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiVersion.to_json(registry_models.ApiVersion()) - - request = registry_service.GetApiVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiVersion() - - client.get_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiVersionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_api_version(request) - - -def test_get_api_version_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_api_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*}" % client.transport._host, args[1]) - - -def test_get_api_version_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_api_version( - registry_service.GetApiVersionRequest(), - name='name_value', - ) - - -def test_get_api_version_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiVersionRequest, - dict, -]) -def test_create_api_version_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request_init["api_version"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_api_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -def test_create_api_version_rest_required_fields(request_type=registry_service.CreateApiVersionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["api_version_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "apiVersionId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "apiVersionId" in jsonified_request - assert jsonified_request["apiVersionId"] == request_init["api_version_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["apiVersionId"] = 'api_version_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_version._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("api_version_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "apiVersionId" in jsonified_request - assert jsonified_request["apiVersionId"] == 'api_version_id_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_api_version(request) - - expected_params = [ - ( - "apiVersionId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_api_version_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_api_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(("apiVersionId", )) & set(("parent", "apiVersion", "apiVersionId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_api_version_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_create_api_version") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.CreateApiVersionRequest.pb(registry_service.CreateApiVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiVersion.to_json(registry_models.ApiVersion()) - - request = registry_service.CreateApiVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiVersion() - - client.create_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiVersionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request_init["api_version"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_api_version(request) - - -def test_create_api_version_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - api_version=registry_models.ApiVersion(name='name_value'), - api_version_id='api_version_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_api_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/versions" % client.transport._host, args[1]) - - -def test_create_api_version_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api_version( - registry_service.CreateApiVersionRequest(), - parent='parent_value', - api_version=registry_models.ApiVersion(name='name_value'), - api_version_id='api_version_id_value', - ) - - -def test_create_api_version_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiVersionRequest, - dict, -]) -def test_update_api_version_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'api_version': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'}} - request_init["api_version"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion( - name='name_value', - display_name='display_name_value', - description='description_value', - state='state_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_api_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiVersion) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.state == 'state_value' - - -def test_update_api_version_rest_required_fields(request_type=registry_service.UpdateApiVersionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_version._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_api_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_api_version_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_api_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("apiVersion", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_api_version_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_update_api_version") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.UpdateApiVersionRequest.pb(registry_service.UpdateApiVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiVersion.to_json(registry_models.ApiVersion()) - - request = registry_service.UpdateApiVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiVersion() - - client.update_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiVersionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'api_version': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'}} - request_init["api_version"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'state': 'state_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_api_version(request) - - -def test_update_api_version_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'api_version': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - api_version=registry_models.ApiVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiVersion.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_api_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{api_version.name=projects/*/locations/*/apis/*/versions/*}" % client.transport._host, args[1]) - - -def test_update_api_version_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api_version( - registry_service.UpdateApiVersionRequest(), - api_version=registry_models.ApiVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_api_version_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiVersionRequest, - dict, -]) -def test_delete_api_version_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_api_version(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_version_rest_required_fields(request_type=registry_service.DeleteApiVersionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_version._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_api_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_api_version_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_api_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_api_version_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_version") as pre: - pre.assert_not_called() - pb_message = registry_service.DeleteApiVersionRequest.pb(registry_service.DeleteApiVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = registry_service.DeleteApiVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_api_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_api_version_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiVersionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_api_version(request) - - -def test_delete_api_version_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_api_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*}" % client.transport._host, args[1]) - - -def test_delete_api_version_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_version( - registry_service.DeleteApiVersionRequest(), - name='name_value', - ) - - -def test_delete_api_version_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiSpecsRequest, - dict, -]) -def test_list_api_specs_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiSpecsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiSpecsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_api_specs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiSpecsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_specs_rest_required_fields(request_type=registry_service.ListApiSpecsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_specs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_specs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiSpecsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_service.ListApiSpecsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_api_specs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_api_specs_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_api_specs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_api_specs_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_specs") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_specs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ListApiSpecsRequest.pb(registry_service.ListApiSpecsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_service.ListApiSpecsResponse.to_json(registry_service.ListApiSpecsResponse()) - - request = registry_service.ListApiSpecsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_service.ListApiSpecsResponse() - - client.list_api_specs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_api_specs_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiSpecsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_api_specs(request) - - -def test_list_api_specs_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiSpecsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiSpecsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_api_specs(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs" % client.transport._host, args[1]) - - -def test_list_api_specs_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_api_specs( - registry_service.ListApiSpecsRequest(), - parent='parent_value', - ) - - -def test_list_api_specs_rest_pager(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(registry_service.ListApiSpecsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - - pager = client.list_api_specs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiSpec) - for i in results) - - pages = list(client.list_api_specs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetApiSpecRequest, - dict, -]) -def test_get_api_spec_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_api_spec(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_get_api_spec_rest_required_fields(request_type=registry_service.GetApiSpecRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_api_spec(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_api_spec_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_api_spec._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_api_spec_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_spec") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_spec") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.GetApiSpecRequest.pb(registry_service.GetApiSpecRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) - - request = registry_service.GetApiSpecRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiSpec() - - client.get_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiSpecRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_api_spec(request) - - -def test_get_api_spec_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_api_spec(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}" % client.transport._host, args[1]) - - -def test_get_api_spec_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_api_spec( - registry_service.GetApiSpecRequest(), - name='name_value', - ) - - -def test_get_api_spec_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetApiSpecContentsRequest, - dict, -]) -def test_get_api_spec_contents_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_api_spec_contents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_get_api_spec_contents_rest_required_fields(request_type=registry_service.GetApiSpecContentsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec_contents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_spec_contents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_api_spec_contents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_api_spec_contents_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_api_spec_contents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_api_spec_contents_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_spec_contents") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_spec_contents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.GetApiSpecContentsRequest.pb(registry_service.GetApiSpecContentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = registry_service.GetApiSpecContentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.get_api_spec_contents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_api_spec_contents_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiSpecContentsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_api_spec_contents(request) - - -def test_get_api_spec_contents_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_api_spec_contents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:getContents" % client.transport._host, args[1]) - - -def test_get_api_spec_contents_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_api_spec_contents( - registry_service.GetApiSpecContentsRequest(), - name='name_value', - ) - - -def test_get_api_spec_contents_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiSpecRequest, - dict, -]) -def test_create_api_spec_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request_init["api_spec"] = {'name': 'name_value', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_api_spec(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_create_api_spec_rest_required_fields(request_type=registry_service.CreateApiSpecRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["api_spec_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "apiSpecId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_spec._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "apiSpecId" in jsonified_request - assert jsonified_request["apiSpecId"] == request_init["api_spec_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["apiSpecId"] = 'api_spec_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_spec._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("api_spec_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "apiSpecId" in jsonified_request - assert jsonified_request["apiSpecId"] == 'api_spec_id_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_api_spec(request) - - expected_params = [ - ( - "apiSpecId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_api_spec_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_api_spec._get_unset_required_fields({}) - assert set(unset_fields) == (set(("apiSpecId", )) & set(("parent", "apiSpec", "apiSpecId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_api_spec_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_create_api_spec") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api_spec") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.CreateApiSpecRequest.pb(registry_service.CreateApiSpecRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) - - request = registry_service.CreateApiSpecRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiSpec() - - client.create_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiSpecRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - request_init["api_spec"] = {'name': 'name_value', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_api_spec(request) - - -def test_create_api_spec_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - api_spec=registry_models.ApiSpec(name='name_value'), - api_spec_id='api_spec_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_api_spec(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*/versions/*}/specs" % client.transport._host, args[1]) - - -def test_create_api_spec_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api_spec( - registry_service.CreateApiSpecRequest(), - parent='parent_value', - api_spec=registry_models.ApiSpec(name='name_value'), - api_spec_id='api_spec_id_value', - ) - - -def test_create_api_spec_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiSpecRequest, - dict, -]) -def test_update_api_spec_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'api_spec': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'}} - request_init["api_spec"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_api_spec(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_update_api_spec_rest_required_fields(request_type=registry_service.UpdateApiSpecRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_spec._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_spec._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_api_spec(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_api_spec_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_api_spec._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("apiSpec", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_api_spec_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_update_api_spec") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api_spec") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.UpdateApiSpecRequest.pb(registry_service.UpdateApiSpecRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) - - request = registry_service.UpdateApiSpecRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiSpec() - - client.update_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiSpecRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'api_spec': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'}} - request_init["api_spec"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5', 'filename': 'filename_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'source_uri': 'source_uri_value', 'contents': b'contents_blob', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_api_spec(request) - - -def test_update_api_spec_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - - # get arguments that satisfy an http rule for this method - sample_request = {'api_spec': {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'}} - - # get truthy value for each flattened field - mock_args = dict( - api_spec=registry_models.ApiSpec(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_api_spec(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{api_spec.name=projects/*/locations/*/apis/*/versions/*/specs/*}" % client.transport._host, args[1]) - - -def test_update_api_spec_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api_spec( - registry_service.UpdateApiSpecRequest(), - api_spec=registry_models.ApiSpec(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_api_spec_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiSpecRequest, - dict, -]) -def test_delete_api_spec_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_api_spec(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_spec_rest_required_fields(request_type=registry_service.DeleteApiSpecRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_api_spec(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_api_spec_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_api_spec._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_api_spec_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_spec") as pre: - pre.assert_not_called() - pb_message = registry_service.DeleteApiSpecRequest.pb(registry_service.DeleteApiSpecRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = registry_service.DeleteApiSpecRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiSpecRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_api_spec(request) - - -def test_delete_api_spec_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_api_spec(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}" % client.transport._host, args[1]) - - -def test_delete_api_spec_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_spec( - registry_service.DeleteApiSpecRequest(), - name='name_value', - ) - - -def test_delete_api_spec_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.TagApiSpecRevisionRequest, - dict, -]) -def test_tag_api_spec_revision_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.tag_api_spec_revision(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_tag_api_spec_revision_rest_required_fields(request_type=registry_service.TagApiSpecRevisionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request_init["tag"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_spec_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["tag"] = 'tag_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_spec_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "tag" in jsonified_request - assert jsonified_request["tag"] == 'tag_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.tag_api_spec_revision(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_tag_api_spec_revision_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.tag_api_spec_revision._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "tag", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_tag_api_spec_revision_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_tag_api_spec_revision") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_tag_api_spec_revision") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.TagApiSpecRevisionRequest.pb(registry_service.TagApiSpecRevisionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) - - request = registry_service.TagApiSpecRevisionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiSpec() - - client.tag_api_spec_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_tag_api_spec_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.TagApiSpecRevisionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.tag_api_spec_revision(request) - - -def test_tag_api_spec_revision_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiSpecRevisionsRequest, - dict, -]) -def test_list_api_spec_revisions_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiSpecRevisionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiSpecRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_api_spec_revisions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiSpecRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_spec_revisions_rest_required_fields(request_type=registry_service.ListApiSpecRevisionsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_spec_revisions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_spec_revisions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiSpecRevisionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_service.ListApiSpecRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_api_spec_revisions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_api_spec_revisions_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_api_spec_revisions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_api_spec_revisions_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_spec_revisions") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_spec_revisions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ListApiSpecRevisionsRequest.pb(registry_service.ListApiSpecRevisionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_service.ListApiSpecRevisionsResponse.to_json(registry_service.ListApiSpecRevisionsResponse()) - - request = registry_service.ListApiSpecRevisionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_service.ListApiSpecRevisionsResponse() - - client.list_api_spec_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_api_spec_revisions_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiSpecRevisionsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_api_spec_revisions(request) - - -def test_list_api_spec_revisions_rest_pager(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - next_page_token='abc', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[], - next_page_token='def', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - ], - next_page_token='ghi', - ), - registry_service.ListApiSpecRevisionsResponse( - api_specs=[ - registry_models.ApiSpec(), - registry_models.ApiSpec(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(registry_service.ListApiSpecRevisionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - - pager = client.list_api_spec_revisions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiSpec) - for i in results) - - pages = list(client.list_api_spec_revisions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - registry_service.RollbackApiSpecRequest, - dict, -]) -def test_rollback_api_spec_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.rollback_api_spec(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_rollback_api_spec_rest_required_fields(request_type=registry_service.RollbackApiSpecRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request_init["revision_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_spec._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["revisionId"] = 'revision_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_spec._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "revisionId" in jsonified_request - assert jsonified_request["revisionId"] == 'revision_id_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.rollback_api_spec(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_rollback_api_spec_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.rollback_api_spec._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "revisionId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_rollback_api_spec_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_rollback_api_spec") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_rollback_api_spec") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.RollbackApiSpecRequest.pb(registry_service.RollbackApiSpecRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) - - request = registry_service.RollbackApiSpecRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiSpec() - - client.rollback_api_spec(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_rollback_api_spec_rest_bad_request(transport: str = 'rest', request_type=registry_service.RollbackApiSpecRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.rollback_api_spec(request) - - -def test_rollback_api_spec_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiSpecRevisionRequest, - dict, -]) -def test_delete_api_spec_revision_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec( - name='name_value', - filename='filename_value', - description='description_value', - revision_id='revision_id_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - source_uri='source_uri_value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_api_spec_revision(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiSpec) - assert response.name == 'name_value' - assert response.filename == 'filename_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.source_uri == 'source_uri_value' - assert response.contents == b'contents_blob' - - -def test_delete_api_spec_revision_rest_required_fields(request_type=registry_service.DeleteApiSpecRevisionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_spec_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_api_spec_revision(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_api_spec_revision_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_api_spec_revision._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_api_spec_revision_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_delete_api_spec_revision") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_spec_revision") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.DeleteApiSpecRevisionRequest.pb(registry_service.DeleteApiSpecRevisionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiSpec.to_json(registry_models.ApiSpec()) - - request = registry_service.DeleteApiSpecRevisionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiSpec() - - client.delete_api_spec_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_api_spec_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiSpecRevisionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_api_spec_revision(request) - - -def test_delete_api_spec_revision_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiSpec() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/versions/sample4/specs/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiSpec.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_api_spec_revision(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/versions/*/specs/*}:deleteRevision" % client.transport._host, args[1]) - - -def test_delete_api_spec_revision_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_spec_revision( - registry_service.DeleteApiSpecRevisionRequest(), - name='name_value', - ) - - -def test_delete_api_spec_revision_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiDeploymentsRequest, - dict, -]) -def test_list_api_deployments_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiDeploymentsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiDeploymentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_api_deployments(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiDeploymentsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_deployments_rest_required_fields(request_type=registry_service.ListApiDeploymentsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployments._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployments._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiDeploymentsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_service.ListApiDeploymentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_api_deployments(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_api_deployments_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_api_deployments._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_api_deployments_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_deployments") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_deployments") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ListApiDeploymentsRequest.pb(registry_service.ListApiDeploymentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_service.ListApiDeploymentsResponse.to_json(registry_service.ListApiDeploymentsResponse()) - - request = registry_service.ListApiDeploymentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_service.ListApiDeploymentsResponse() - - client.list_api_deployments(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_api_deployments_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiDeploymentsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_api_deployments(request) - - -def test_list_api_deployments_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiDeploymentsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiDeploymentsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_api_deployments(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/deployments" % client.transport._host, args[1]) - - -def test_list_api_deployments_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_api_deployments( - registry_service.ListApiDeploymentsRequest(), - parent='parent_value', - ) - - -def test_list_api_deployments_rest_pager(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(registry_service.ListApiDeploymentsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - - pager = client.list_api_deployments(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiDeployment) - for i in results) - - pages = list(client.list_api_deployments(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetApiDeploymentRequest, - dict, -]) -def test_get_api_deployment_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_api_deployment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_get_api_deployment_rest_required_fields(request_type=registry_service.GetApiDeploymentRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_api_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_api_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_api_deployment_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_api_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_api_deployment_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_get_api_deployment") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_get_api_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.GetApiDeploymentRequest.pb(registry_service.GetApiDeploymentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) - - request = registry_service.GetApiDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiDeployment() - - client.get_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetApiDeploymentRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_api_deployment(request) - - -def test_get_api_deployment_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_api_deployment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/deployments/*}" % client.transport._host, args[1]) - - -def test_get_api_deployment_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_api_deployment( - registry_service.GetApiDeploymentRequest(), - name='name_value', - ) - - -def test_get_api_deployment_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateApiDeploymentRequest, - dict, -]) -def test_create_api_deployment_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request_init["api_deployment"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_api_deployment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_create_api_deployment_rest_required_fields(request_type=registry_service.CreateApiDeploymentRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["api_deployment_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "apiDeploymentId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "apiDeploymentId" in jsonified_request - assert jsonified_request["apiDeploymentId"] == request_init["api_deployment_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["apiDeploymentId"] = 'api_deployment_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_api_deployment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("api_deployment_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "apiDeploymentId" in jsonified_request - assert jsonified_request["apiDeploymentId"] == 'api_deployment_id_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_api_deployment(request) - - expected_params = [ - ( - "apiDeploymentId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_api_deployment_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_api_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("apiDeploymentId", )) & set(("parent", "apiDeployment", "apiDeploymentId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_api_deployment_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_create_api_deployment") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_create_api_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.CreateApiDeploymentRequest.pb(registry_service.CreateApiDeploymentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) - - request = registry_service.CreateApiDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiDeployment() - - client.create_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateApiDeploymentRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - request_init["api_deployment"] = {'name': 'name_value', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_api_deployment(request) - - -def test_create_api_deployment_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/apis/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - api_deployment=registry_models.ApiDeployment(name='name_value'), - api_deployment_id='api_deployment_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_api_deployment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/apis/*}/deployments" % client.transport._host, args[1]) - - -def test_create_api_deployment_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_api_deployment( - registry_service.CreateApiDeploymentRequest(), - parent='parent_value', - api_deployment=registry_models.ApiDeployment(name='name_value'), - api_deployment_id='api_deployment_id_value', - ) - - -def test_create_api_deployment_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.UpdateApiDeploymentRequest, - dict, -]) -def test_update_api_deployment_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'api_deployment': {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'}} - request_init["api_deployment"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_api_deployment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_update_api_deployment_rest_required_fields(request_type=registry_service.UpdateApiDeploymentRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_api_deployment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("allow_missing", "update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "patch", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_api_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_api_deployment_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_api_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("allowMissing", "updateMask", )) & set(("apiDeployment", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_api_deployment_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_update_api_deployment") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_update_api_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.UpdateApiDeploymentRequest.pb(registry_service.UpdateApiDeploymentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) - - request = registry_service.UpdateApiDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiDeployment() - - client.update_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.UpdateApiDeploymentRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'api_deployment': {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'}} - request_init["api_deployment"] = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4', 'display_name': 'display_name_value', 'description': 'description_value', 'revision_id': 'revision_id_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'revision_create_time': {}, 'revision_update_time': {}, 'api_spec_revision': 'api_spec_revision_value', 'endpoint_uri': 'endpoint_uri_value', 'external_channel_uri': 'external_channel_uri_value', 'intended_audience': 'intended_audience_value', 'access_guidance': 'access_guidance_value', 'labels': {}, 'annotations': {}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.update_api_deployment(request) - - -def test_update_api_deployment_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - - # get arguments that satisfy an http rule for this method - sample_request = {'api_deployment': {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - api_deployment=registry_models.ApiDeployment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_api_deployment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{api_deployment.name=projects/*/locations/*/apis/*/deployments/*}" % client.transport._host, args[1]) - - -def test_update_api_deployment_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_api_deployment( - registry_service.UpdateApiDeploymentRequest(), - api_deployment=registry_models.ApiDeployment(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_api_deployment_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiDeploymentRequest, - dict, -]) -def test_delete_api_deployment_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_api_deployment(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_api_deployment_rest_required_fields(request_type=registry_service.DeleteApiDeploymentRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("force", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_api_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_api_deployment_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_api_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(("force", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_api_deployment_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_deployment") as pre: - pre.assert_not_called() - pb_message = registry_service.DeleteApiDeploymentRequest.pb(registry_service.DeleteApiDeploymentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = registry_service.DeleteApiDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiDeploymentRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_api_deployment(request) - - -def test_delete_api_deployment_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_api_deployment(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/deployments/*}" % client.transport._host, args[1]) - - -def test_delete_api_deployment_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_deployment( - registry_service.DeleteApiDeploymentRequest(), - name='name_value', - ) - - -def test_delete_api_deployment_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.TagApiDeploymentRevisionRequest, - dict, -]) -def test_tag_api_deployment_revision_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.tag_api_deployment_revision(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_tag_api_deployment_revision_rest_required_fields(request_type=registry_service.TagApiDeploymentRevisionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request_init["tag"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_deployment_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["tag"] = 'tag_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).tag_api_deployment_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "tag" in jsonified_request - assert jsonified_request["tag"] == 'tag_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.tag_api_deployment_revision(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_tag_api_deployment_revision_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.tag_api_deployment_revision._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "tag", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_tag_api_deployment_revision_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_tag_api_deployment_revision") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_tag_api_deployment_revision") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.TagApiDeploymentRevisionRequest.pb(registry_service.TagApiDeploymentRevisionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) - - request = registry_service.TagApiDeploymentRevisionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiDeployment() - - client.tag_api_deployment_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_tag_api_deployment_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.TagApiDeploymentRevisionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.tag_api_deployment_revision(request) - - -def test_tag_api_deployment_revision_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListApiDeploymentRevisionsRequest, - dict, -]) -def test_list_api_deployment_revisions_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiDeploymentRevisionsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListApiDeploymentRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_api_deployment_revisions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListApiDeploymentRevisionsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_api_deployment_revisions_rest_required_fields(request_type=registry_service.ListApiDeploymentRevisionsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployment_revisions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_api_deployment_revisions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_service.ListApiDeploymentRevisionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_service.ListApiDeploymentRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_api_deployment_revisions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_api_deployment_revisions_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_api_deployment_revisions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", )) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_api_deployment_revisions_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_list_api_deployment_revisions") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_list_api_deployment_revisions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ListApiDeploymentRevisionsRequest.pb(registry_service.ListApiDeploymentRevisionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_service.ListApiDeploymentRevisionsResponse.to_json(registry_service.ListApiDeploymentRevisionsResponse()) - - request = registry_service.ListApiDeploymentRevisionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_service.ListApiDeploymentRevisionsResponse() - - client.list_api_deployment_revisions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_api_deployment_revisions_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListApiDeploymentRevisionsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_api_deployment_revisions(request) - - -def test_list_api_deployment_revisions_rest_pager(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - next_page_token='abc', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[], - next_page_token='def', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - ], - next_page_token='ghi', - ), - registry_service.ListApiDeploymentRevisionsResponse( - api_deployments=[ - registry_models.ApiDeployment(), - registry_models.ApiDeployment(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(registry_service.ListApiDeploymentRevisionsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - - pager = client.list_api_deployment_revisions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.ApiDeployment) - for i in results) - - pages = list(client.list_api_deployment_revisions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - registry_service.RollbackApiDeploymentRequest, - dict, -]) -def test_rollback_api_deployment_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.rollback_api_deployment(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_rollback_api_deployment_rest_required_fields(request_type=registry_service.RollbackApiDeploymentRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request_init["revision_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["revisionId"] = 'revision_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).rollback_api_deployment._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "revisionId" in jsonified_request - assert jsonified_request["revisionId"] == 'revision_id_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.rollback_api_deployment(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_rollback_api_deployment_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.rollback_api_deployment._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "revisionId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_rollback_api_deployment_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_rollback_api_deployment") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_rollback_api_deployment") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.RollbackApiDeploymentRequest.pb(registry_service.RollbackApiDeploymentRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) - - request = registry_service.RollbackApiDeploymentRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiDeployment() - - client.rollback_api_deployment(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_rollback_api_deployment_rest_bad_request(transport: str = 'rest', request_type=registry_service.RollbackApiDeploymentRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.rollback_api_deployment(request) - - -def test_rollback_api_deployment_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteApiDeploymentRevisionRequest, - dict, -]) -def test_delete_api_deployment_revision_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment( - name='name_value', - display_name='display_name_value', - description='description_value', - revision_id='revision_id_value', - api_spec_revision='api_spec_revision_value', - endpoint_uri='endpoint_uri_value', - external_channel_uri='external_channel_uri_value', - intended_audience='intended_audience_value', - access_guidance='access_guidance_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_api_deployment_revision(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.ApiDeployment) - assert response.name == 'name_value' - assert response.display_name == 'display_name_value' - assert response.description == 'description_value' - assert response.revision_id == 'revision_id_value' - assert response.api_spec_revision == 'api_spec_revision_value' - assert response.endpoint_uri == 'endpoint_uri_value' - assert response.external_channel_uri == 'external_channel_uri_value' - assert response.intended_audience == 'intended_audience_value' - assert response.access_guidance == 'access_guidance_value' - - -def test_delete_api_deployment_revision_rest_required_fields(request_type=registry_service.DeleteApiDeploymentRevisionRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_api_deployment_revision._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_api_deployment_revision(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_api_deployment_revision_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_api_deployment_revision._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_api_deployment_revision_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_delete_api_deployment_revision") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_api_deployment_revision") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.DeleteApiDeploymentRevisionRequest.pb(registry_service.DeleteApiDeploymentRevisionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.ApiDeployment.to_json(registry_models.ApiDeployment()) - - request = registry_service.DeleteApiDeploymentRevisionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.ApiDeployment() - - client.delete_api_deployment_revision(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_delete_api_deployment_revision_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteApiDeploymentRevisionRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_api_deployment_revision(request) - - -def test_delete_api_deployment_revision_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.ApiDeployment() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/apis/sample3/deployments/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.ApiDeployment.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_api_deployment_revision(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/apis/*/deployments/*}:deleteRevision" % client.transport._host, args[1]) - - -def test_delete_api_deployment_revision_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_api_deployment_revision( - registry_service.DeleteApiDeploymentRevisionRequest(), - name='name_value', - ) - - -def test_delete_api_deployment_revision_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ListArtifactsRequest, - dict, -]) -def test_list_artifacts_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListArtifactsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListArtifactsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_artifacts(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListArtifactsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_artifacts_rest_required_fields(request_type=registry_service.ListArtifactsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_artifacts._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_artifacts._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_service.ListArtifactsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_service.ListArtifactsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_artifacts(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_artifacts_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_artifacts._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_artifacts_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_list_artifacts") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_list_artifacts") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ListArtifactsRequest.pb(registry_service.ListArtifactsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_service.ListArtifactsResponse.to_json(registry_service.ListArtifactsResponse()) - - request = registry_service.ListArtifactsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_service.ListArtifactsResponse() - - client.list_artifacts(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_artifacts_rest_bad_request(transport: str = 'rest', request_type=registry_service.ListArtifactsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_artifacts(request) - - -def test_list_artifacts_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_service.ListArtifactsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_service.ListArtifactsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_artifacts(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/artifacts" % client.transport._host, args[1]) - - -def test_list_artifacts_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_artifacts( - registry_service.ListArtifactsRequest(), - parent='parent_value', - ) - - -def test_list_artifacts_rest_pager(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - registry_models.Artifact(), - ], - next_page_token='abc', - ), - registry_service.ListArtifactsResponse( - artifacts=[], - next_page_token='def', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - ], - next_page_token='ghi', - ), - registry_service.ListArtifactsResponse( - artifacts=[ - registry_models.Artifact(), - registry_models.Artifact(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(registry_service.ListArtifactsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode('UTF-8') - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - pager = client.list_artifacts(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, registry_models.Artifact) - for i in results) - - pages = list(client.list_artifacts(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetArtifactRequest, - dict, -]) -def test_get_artifact_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_artifact(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -def test_get_artifact_rest_required_fields(request_type=registry_service.GetArtifactRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_artifact(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_artifact_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_artifact._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_artifact_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_get_artifact") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_get_artifact") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.GetArtifactRequest.pb(registry_service.GetArtifactRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.Artifact.to_json(registry_models.Artifact()) - - request = registry_service.GetArtifactRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.Artifact() - - client.get_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetArtifactRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_artifact(request) - - -def test_get_artifact_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_artifact(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/artifacts/*}" % client.transport._host, args[1]) - - -def test_get_artifact_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_artifact( - registry_service.GetArtifactRequest(), - name='name_value', - ) - - -def test_get_artifact_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.GetArtifactContentsRequest, - dict, -]) -def test_get_artifact_contents_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody( - content_type='content_type_value', - data=b'data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_artifact_contents(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, httpbody_pb2.HttpBody) - assert response.content_type == 'content_type_value' - assert response.data == b'data_blob' - - -def test_get_artifact_contents_rest_required_fields(request_type=registry_service.GetArtifactContentsRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact_contents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_artifact_contents._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_artifact_contents(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_artifact_contents_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_artifact_contents._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_artifact_contents_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_get_artifact_contents") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_get_artifact_contents") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.GetArtifactContentsRequest.pb(registry_service.GetArtifactContentsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson(httpbody_pb2.HttpBody()) - - request = registry_service.GetArtifactContentsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = httpbody_pb2.HttpBody() - - client.get_artifact_contents(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_artifact_contents_rest_bad_request(transport: str = 'rest', request_type=registry_service.GetArtifactContentsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_artifact_contents(request) - - -def test_get_artifact_contents_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = httpbody_pb2.HttpBody() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = return_value - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_artifact_contents(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/artifacts/*}:getContents" % client.transport._host, args[1]) - - -def test_get_artifact_contents_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_artifact_contents( - registry_service.GetArtifactContentsRequest(), - name='name_value', - ) - - -def test_get_artifact_contents_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.CreateArtifactRequest, - dict, -]) -def test_create_artifact_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["artifact"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_artifact(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -def test_create_artifact_rest_required_fields(request_type=registry_service.CreateArtifactRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["artifact_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "artifactId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_artifact._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "artifactId" in jsonified_request - assert jsonified_request["artifactId"] == request_init["artifact_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["artifactId"] = 'artifact_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_artifact._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("artifact_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "artifactId" in jsonified_request - assert jsonified_request["artifactId"] == 'artifact_id_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_artifact(request) - - expected_params = [ - ( - "artifactId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_artifact_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_artifact._get_unset_required_fields({}) - assert set(unset_fields) == (set(("artifactId", )) & set(("parent", "artifact", "artifactId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_artifact_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_create_artifact") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_create_artifact") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.CreateArtifactRequest.pb(registry_service.CreateArtifactRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.Artifact.to_json(registry_models.Artifact()) - - request = registry_service.CreateArtifactRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.Artifact() - - client.create_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.CreateArtifactRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["artifact"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_artifact(request) - - -def test_create_artifact_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - artifact=registry_models.Artifact(name='name_value'), - artifact_id='artifact_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_artifact(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*}/artifacts" % client.transport._host, args[1]) - - -def test_create_artifact_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_artifact( - registry_service.CreateArtifactRequest(), - parent='parent_value', - artifact=registry_models.Artifact(name='name_value'), - artifact_id='artifact_id_value', - ) - - -def test_create_artifact_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.ReplaceArtifactRequest, - dict, -]) -def test_replace_artifact_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'artifact': {'name': 'projects/sample1/locations/sample2/artifacts/sample3'}} - request_init["artifact"] = {'name': 'projects/sample1/locations/sample2/artifacts/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact( - name='name_value', - mime_type='mime_type_value', - size_bytes=1089, - hash_='hash__value', - contents=b'contents_blob', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.replace_artifact(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, registry_models.Artifact) - assert response.name == 'name_value' - assert response.mime_type == 'mime_type_value' - assert response.size_bytes == 1089 - assert response.hash_ == 'hash__value' - assert response.contents == b'contents_blob' - - -def test_replace_artifact_rest_required_fields(request_type=registry_service.ReplaceArtifactRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).replace_artifact._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).replace_artifact._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "put", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.replace_artifact(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_replace_artifact_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.replace_artifact._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("artifact", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_replace_artifact_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "post_replace_artifact") as post, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_replace_artifact") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = registry_service.ReplaceArtifactRequest.pb(registry_service.ReplaceArtifactRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - req.return_value._content = registry_models.Artifact.to_json(registry_models.Artifact()) - - request = registry_service.ReplaceArtifactRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = registry_models.Artifact() - - client.replace_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_replace_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.ReplaceArtifactRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'artifact': {'name': 'projects/sample1/locations/sample2/artifacts/sample3'}} - request_init["artifact"] = {'name': 'projects/sample1/locations/sample2/artifacts/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'update_time': {}, 'mime_type': 'mime_type_value', 'size_bytes': 1089, 'hash_': 'hash__value', 'contents': b'contents_blob'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.replace_artifact(request) - - -def test_replace_artifact_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = registry_models.Artifact() - - # get arguments that satisfy an http rule for this method - sample_request = {'artifact': {'name': 'projects/sample1/locations/sample2/artifacts/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - artifact=registry_models.Artifact(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = registry_models.Artifact.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.replace_artifact(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{artifact.name=projects/*/locations/*/artifacts/*}" % client.transport._host, args[1]) - - -def test_replace_artifact_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.replace_artifact( - registry_service.ReplaceArtifactRequest(), - artifact=registry_models.Artifact(name='name_value'), - ) - - -def test_replace_artifact_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - registry_service.DeleteArtifactRequest, - dict, -]) -def test_delete_artifact_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.delete_artifact(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_artifact_rest_required_fields(request_type=registry_service.DeleteArtifactRequest): - transport_class = transports.RegistryRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_artifact._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).delete_artifact._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = None - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "delete", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_artifact(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_artifact_rest_unset_required_fields(): - transport = transports.RegistryRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_artifact._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_artifact_rest_interceptors(null_interceptor): - transport = transports.RegistryRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RegistryRestInterceptor(), - ) - client = RegistryClient(transport=transport) - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.RegistryRestInterceptor, "pre_delete_artifact") as pre: - pre.assert_not_called() - pb_message = registry_service.DeleteArtifactRequest.pb(registry_service.DeleteArtifactRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = Response() - req.return_value.status_code = 200 - req.return_value.request = PreparedRequest() - - request = registry_service.DeleteArtifactRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_artifact(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_artifact_rest_bad_request(transport: str = 'rest', request_type=registry_service.DeleteArtifactRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_artifact(request) - - -def test_delete_artifact_rest_flattened(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/artifacts/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '' - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.delete_artifact(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/artifacts/*}" % client.transport._host, args[1]) - - -def test_delete_artifact_rest_flattened_error(transport: str = 'rest'): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_artifact( - registry_service.DeleteArtifactRequest(), - name='name_value', - ) - - -def test_delete_artifact_rest_error(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.RegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistryClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.RegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RegistryClient( - 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 = RegistryClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RegistryClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RegistryClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegistryGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.RegistryGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.RegistryGrpcTransport, - transports.RegistryGrpcAsyncIOTransport, - transports.RegistryRestTransport, -]) -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", - "rest", -]) -def test_transport_kind(transport_name): - transport = RegistryClient.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 = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.RegistryGrpcTransport, - ) - -def test_registry_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.RegistryTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_registry_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.apigee_registry_v1.services.registry.transports.RegistryTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.RegistryTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_apis', - 'get_api', - 'create_api', - 'update_api', - 'delete_api', - 'list_api_versions', - 'get_api_version', - 'create_api_version', - 'update_api_version', - 'delete_api_version', - 'list_api_specs', - 'get_api_spec', - 'get_api_spec_contents', - 'create_api_spec', - 'update_api_spec', - 'delete_api_spec', - 'tag_api_spec_revision', - 'list_api_spec_revisions', - 'rollback_api_spec', - 'delete_api_spec_revision', - 'list_api_deployments', - 'get_api_deployment', - 'create_api_deployment', - 'update_api_deployment', - 'delete_api_deployment', - 'tag_api_deployment_revision', - 'list_api_deployment_revisions', - 'rollback_api_deployment', - 'delete_api_deployment_revision', - 'list_artifacts', - 'get_artifact', - 'get_artifact_contents', - 'create_artifact', - 'replace_artifact', - 'delete_artifact', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - '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() - - # Catch all for all remaining methods and properties - remainder = [ - 'kind', - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() - - -def test_registry_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.apigee_registry_v1.services.registry.transports.RegistryTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistryTransport( - 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_registry_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.apigee_registry_v1.services.registry.transports.RegistryTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.RegistryTransport() - adc.assert_called_once() - - -def test_registry_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) - RegistryClient() - 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.RegistryGrpcTransport, - transports.RegistryGrpcAsyncIOTransport, - ], -) -def test_registry_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.RegistryGrpcTransport, - transports.RegistryGrpcAsyncIOTransport, - transports.RegistryRestTransport, - ], -) -def test_registry_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.RegistryGrpcTransport, grpc_helpers), - (transports.RegistryGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_registry_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( - "apigeeregistry.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="apigeeregistry.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.RegistryGrpcTransport, transports.RegistryGrpcAsyncIOTransport]) -def test_registry_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 - ) - -def test_registry_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.RegistryRestTransport ( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) - - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_registry_host_no_port(transport_name): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://apigeeregistry.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_registry_host_with_port(transport_name): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='apigeeregistry.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'apigeeregistry.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://apigeeregistry.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_registry_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = RegistryClient( - credentials=creds1, - transport=transport_name, - ) - client2 = RegistryClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_apis._session - session2 = client2.transport.list_apis._session - assert session1 != session2 - session1 = client1.transport.get_api._session - session2 = client2.transport.get_api._session - assert session1 != session2 - session1 = client1.transport.create_api._session - session2 = client2.transport.create_api._session - assert session1 != session2 - session1 = client1.transport.update_api._session - session2 = client2.transport.update_api._session - assert session1 != session2 - session1 = client1.transport.delete_api._session - session2 = client2.transport.delete_api._session - assert session1 != session2 - session1 = client1.transport.list_api_versions._session - session2 = client2.transport.list_api_versions._session - assert session1 != session2 - session1 = client1.transport.get_api_version._session - session2 = client2.transport.get_api_version._session - assert session1 != session2 - session1 = client1.transport.create_api_version._session - session2 = client2.transport.create_api_version._session - assert session1 != session2 - session1 = client1.transport.update_api_version._session - session2 = client2.transport.update_api_version._session - assert session1 != session2 - session1 = client1.transport.delete_api_version._session - session2 = client2.transport.delete_api_version._session - assert session1 != session2 - session1 = client1.transport.list_api_specs._session - session2 = client2.transport.list_api_specs._session - assert session1 != session2 - session1 = client1.transport.get_api_spec._session - session2 = client2.transport.get_api_spec._session - assert session1 != session2 - session1 = client1.transport.get_api_spec_contents._session - session2 = client2.transport.get_api_spec_contents._session - assert session1 != session2 - session1 = client1.transport.create_api_spec._session - session2 = client2.transport.create_api_spec._session - assert session1 != session2 - session1 = client1.transport.update_api_spec._session - session2 = client2.transport.update_api_spec._session - assert session1 != session2 - session1 = client1.transport.delete_api_spec._session - session2 = client2.transport.delete_api_spec._session - assert session1 != session2 - session1 = client1.transport.tag_api_spec_revision._session - session2 = client2.transport.tag_api_spec_revision._session - assert session1 != session2 - session1 = client1.transport.list_api_spec_revisions._session - session2 = client2.transport.list_api_spec_revisions._session - assert session1 != session2 - session1 = client1.transport.rollback_api_spec._session - session2 = client2.transport.rollback_api_spec._session - assert session1 != session2 - session1 = client1.transport.delete_api_spec_revision._session - session2 = client2.transport.delete_api_spec_revision._session - assert session1 != session2 - session1 = client1.transport.list_api_deployments._session - session2 = client2.transport.list_api_deployments._session - assert session1 != session2 - session1 = client1.transport.get_api_deployment._session - session2 = client2.transport.get_api_deployment._session - assert session1 != session2 - session1 = client1.transport.create_api_deployment._session - session2 = client2.transport.create_api_deployment._session - assert session1 != session2 - session1 = client1.transport.update_api_deployment._session - session2 = client2.transport.update_api_deployment._session - assert session1 != session2 - session1 = client1.transport.delete_api_deployment._session - session2 = client2.transport.delete_api_deployment._session - assert session1 != session2 - session1 = client1.transport.tag_api_deployment_revision._session - session2 = client2.transport.tag_api_deployment_revision._session - assert session1 != session2 - session1 = client1.transport.list_api_deployment_revisions._session - session2 = client2.transport.list_api_deployment_revisions._session - assert session1 != session2 - session1 = client1.transport.rollback_api_deployment._session - session2 = client2.transport.rollback_api_deployment._session - assert session1 != session2 - session1 = client1.transport.delete_api_deployment_revision._session - session2 = client2.transport.delete_api_deployment_revision._session - assert session1 != session2 - session1 = client1.transport.list_artifacts._session - session2 = client2.transport.list_artifacts._session - assert session1 != session2 - session1 = client1.transport.get_artifact._session - session2 = client2.transport.get_artifact._session - assert session1 != session2 - session1 = client1.transport.get_artifact_contents._session - session2 = client2.transport.get_artifact_contents._session - assert session1 != session2 - session1 = client1.transport.create_artifact._session - session2 = client2.transport.create_artifact._session - assert session1 != session2 - session1 = client1.transport.replace_artifact._session - session2 = client2.transport.replace_artifact._session - assert session1 != session2 - session1 = client1.transport.delete_artifact._session - session2 = client2.transport.delete_artifact._session - assert session1 != session2 -def test_registry_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegistryGrpcTransport( - 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_registry_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.RegistryGrpcAsyncIOTransport( - 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.RegistryGrpcTransport, transports.RegistryGrpcAsyncIOTransport]) -def test_registry_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.RegistryGrpcTransport, transports.RegistryGrpcAsyncIOTransport]) -def test_registry_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_api_path(): - project = "squid" - location = "clam" - api = "whelk" - expected = "projects/{project}/locations/{location}/apis/{api}".format(project=project, location=location, api=api, ) - actual = RegistryClient.api_path(project, location, api) - assert expected == actual - - -def test_parse_api_path(): - expected = { - "project": "octopus", - "location": "oyster", - "api": "nudibranch", - } - path = RegistryClient.api_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_api_path(path) - assert expected == actual - -def test_api_deployment_path(): - project = "cuttlefish" - location = "mussel" - api = "winkle" - deployment = "nautilus" - expected = "projects/{project}/locations/{location}/apis/{api}/deployments/{deployment}".format(project=project, location=location, api=api, deployment=deployment, ) - actual = RegistryClient.api_deployment_path(project, location, api, deployment) - assert expected == actual - - -def test_parse_api_deployment_path(): - expected = { - "project": "scallop", - "location": "abalone", - "api": "squid", - "deployment": "clam", - } - path = RegistryClient.api_deployment_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_api_deployment_path(path) - assert expected == actual - -def test_api_spec_path(): - project = "whelk" - location = "octopus" - api = "oyster" - version = "nudibranch" - spec = "cuttlefish" - expected = "projects/{project}/locations/{location}/apis/{api}/versions/{version}/specs/{spec}".format(project=project, location=location, api=api, version=version, spec=spec, ) - actual = RegistryClient.api_spec_path(project, location, api, version, spec) - assert expected == actual - - -def test_parse_api_spec_path(): - expected = { - "project": "mussel", - "location": "winkle", - "api": "nautilus", - "version": "scallop", - "spec": "abalone", - } - path = RegistryClient.api_spec_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_api_spec_path(path) - assert expected == actual - -def test_api_version_path(): - project = "squid" - location = "clam" - api = "whelk" - version = "octopus" - expected = "projects/{project}/locations/{location}/apis/{api}/versions/{version}".format(project=project, location=location, api=api, version=version, ) - actual = RegistryClient.api_version_path(project, location, api, version) - assert expected == actual - - -def test_parse_api_version_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "api": "cuttlefish", - "version": "mussel", - } - path = RegistryClient.api_version_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_api_version_path(path) - assert expected == actual - -def test_artifact_path(): - project = "winkle" - location = "nautilus" - artifact = "scallop" - expected = "projects/{project}/locations/{location}/artifacts/{artifact}".format(project=project, location=location, artifact=artifact, ) - actual = RegistryClient.artifact_path(project, location, artifact) - assert expected == actual - - -def test_parse_artifact_path(): - expected = { - "project": "abalone", - "location": "squid", - "artifact": "clam", - } - path = RegistryClient.artifact_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_artifact_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = RegistryClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = RegistryClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = RegistryClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = RegistryClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = RegistryClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = RegistryClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = RegistryClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = RegistryClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = RegistryClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = RegistryClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = RegistryClient.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(transports.RegistryTransport, '_prep_wrapped_messages') as prep: - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.RegistryTransport, '_prep_wrapped_messages') as prep: - transport_class = RegistryClient.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 = RegistryAsyncClient( - 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_get_location_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.GetLocationRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_list_locations_rest_bad_request(transport: str = 'rest', request_type=locations_pb2.ListLocationsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_get_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.GetIamPolicyRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_set_iam_policy_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.SetIamPolicyRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - -def test_test_iam_permissions_rest_bad_request(transport: str = 'rest', request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/apis/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'resource': 'projects/sample1/locations/sample2/apis/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - -def test_cancel_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.CancelOperationRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.cancel_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.CancelOperationRequest, - dict, -]) -def test_cancel_operation_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.cancel_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_delete_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.DeleteOperationRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.delete_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.DeleteOperationRequest, - dict, -]) -def test_delete_operation_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = '{}' - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.delete_operation(request) - - # Establish that the response is the type that we expect. - assert response is None - -def test_get_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_list_operations_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.ListOperationsRequest): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_operations(request) - -@pytest.mark.parametrize("request_type", [ - operations_pb2.ListOperationsRequest, - dict, -]) -def test_list_operations_rest(request_type): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_operations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - - -def test_delete_operation(transport: str = "grpc"): - client = RegistryClient( - 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 = RegistryAsyncClient( - 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 = RegistryClient( - 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 = RegistryAsyncClient( - 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 = RegistryClient( - 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 = RegistryAsyncClient( - 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 = RegistryClient( - 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 = RegistryAsyncClient( - 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 = RegistryClient( - 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 = RegistryAsyncClient( - 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"] - -def test_cancel_operation_from_dict(): - client = RegistryClient( - 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 - - response = client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_cancel_operation_from_dict_async(): - client = RegistryAsyncClient( - 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 = grpc_helpers_async.FakeUnaryUnaryCall( - None - ) - response = await client.cancel_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_operation(transport: str = "grpc"): - client = RegistryClient( - 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.GetOperationRequest() - - # 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 - - # 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 = RegistryAsyncClient( - 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.GetOperationRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = RegistryClient( - 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.GetOperationRequest() - request.name = "locations" - - # 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() - - 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 - - # 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_get_operation_field_headers_async(): - client = RegistryAsyncClient( - 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.GetOperationRequest() - request.name = "locations" - - # 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # 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={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_operation_from_dict_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # 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() - - -def test_list_operations(transport: str = "grpc"): - client = RegistryClient( - 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.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 - - # 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 = RegistryAsyncClient( - 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.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 = 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) - -def test_list_operations_field_headers(): - client = RegistryClient( - 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.ListOperationsRequest() - request.name = "locations" - - # 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() - - 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"] -@pytest.mark.asyncio -async def test_list_operations_field_headers_async(): - client = RegistryAsyncClient( - 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.ListOperationsRequest() - request.name = "locations" - - # 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_operations_from_dict(): - client = RegistryClient( - 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 = operations_pb2.ListOperationsResponse() - - response = client.list_operations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_operations_from_dict_async(): - client = RegistryAsyncClient( - 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_list_locations(transport: str = "grpc"): - client = RegistryClient( - 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 = locations_pb2.ListLocationsRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc"): - client = RegistryAsyncClient( - 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 = locations_pb2.ListLocationsRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = RegistryClient( - 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.ListLocationsRequest() - request.name = "locations" - - # 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() - - 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"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = RegistryAsyncClient( - 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.ListLocationsRequest() - request.name = "locations" - - # 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = RegistryClient( - 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.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = RegistryAsyncClient( - 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_get_location(transport: str = "grpc"): - client = RegistryClient( - 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 = locations_pb2.GetLocationRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = RegistryAsyncClient( - 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 = locations_pb2.GetLocationRequest() - - # 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = RegistryClient( - 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" - - # 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() - - 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"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = RegistryAsyncClient( - 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" - - # 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_get_location_from_dict(): - client = RegistryClient( - 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() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = RegistryAsyncClient( - 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.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = RegistryClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = RegistryAsyncClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = RegistryClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = RegistryAsyncClient( - 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 = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - -def test_get_iam_policy(transport: str = "grpc"): - client = RegistryClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = RegistryAsyncClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = RegistryClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = RegistryAsyncClient( - 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 = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -def test_test_iam_permissions(transport: str = "grpc"): - client = RegistryClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = RegistryAsyncClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = RegistryClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = RegistryAsyncClient( - 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 = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = RegistryAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -def test_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - with mock.patch.object(type(getattr(client.transport, close_name)), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = RegistryClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport - ) - # Test client calls underlying transport. - with mock.patch.object(type(client.transport), "close") as close: - close.assert_not_called() - with client: - pass - close.assert_called() - -@pytest.mark.parametrize("client_class,transport_class", [ - (RegistryClient, transports.RegistryGrpcTransport), - (RegistryAsyncClient, transports.RegistryGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - )