From 195f088cb78f7a07925c0777d7d06d4f1b013efb Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 13 Oct 2023 18:06:40 +0000 Subject: [PATCH 1/2] chore: Update gapic-generator-python to v1.11.7 PiperOrigin-RevId: 573230664 Source-Link: https://github.com/googleapis/googleapis/commit/93beed334607e70709cc60e6145be65fdc8ec386 Source-Link: https://github.com/googleapis/googleapis-gen/commit/f4a4edaa8057639fcf6adf9179872280d1a8f651 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiZjRhNGVkYWE4MDU3NjM5ZmNmNmFkZjkxNzk4NzIyODBkMWE4ZjY1MSJ9 --- 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 + owl-bot-staging/v1/docs/_static/custom.css | 3 + .../v1/docs/asset_v1/asset_service.rst | 10 + owl-bot-staging/v1/docs/asset_v1/services.rst | 6 + owl-bot-staging/v1/docs/asset_v1/types.rst | 6 + owl-bot-staging/v1/docs/conf.py | 376 + owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/asset/__init__.py | 185 + .../v1/google/cloud/asset/gapic_version.py | 16 + .../v1/google/cloud/asset/py.typed | 2 + .../v1/google/cloud/asset_v1/__init__.py | 186 + .../google/cloud/asset_v1/gapic_metadata.json | 373 + .../v1/google/cloud/asset_v1/gapic_version.py | 16 + .../v1/google/cloud/asset_v1/py.typed | 2 + .../cloud/asset_v1/services/__init__.py | 15 + .../services/asset_service/__init__.py | 22 + .../services/asset_service/async_client.py | 3169 ++++ .../asset_v1/services/asset_service/client.py | 3329 ++++ .../asset_v1/services/asset_service/pagers.py | 866 + .../asset_service/transports/__init__.py | 38 + .../services/asset_service/transports/base.py | 580 + .../services/asset_service/transports/grpc.py | 959 ++ .../asset_service/transports/grpc_asyncio.py | 958 ++ .../services/asset_service/transports/rest.py | 2899 ++++ .../google/cloud/asset_v1/types/__init__.py | 180 + .../cloud/asset_v1/types/asset_service.py | 4036 +++++ .../v1/google/cloud/asset_v1/types/assets.py | 1683 ++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 184 + ..._asset_service_analyze_iam_policy_async.py | 55 + ...ce_analyze_iam_policy_longrunning_async.py | 63 + ...ice_analyze_iam_policy_longrunning_sync.py | 63 + ...d_asset_service_analyze_iam_policy_sync.py | 55 + ...erated_asset_service_analyze_move_async.py | 53 + ...nerated_asset_service_analyze_move_sync.py | 53 + ...sset_service_analyze_org_policies_async.py | 54 + ...asset_service_analyze_org_policies_sync.py | 54 + ...nalyze_org_policy_governed_assets_async.py | 54 + ...analyze_org_policy_governed_assets_sync.py | 54 + ...ze_org_policy_governed_containers_async.py | 54 + ...yze_org_policy_governed_containers_sync.py | 54 + ..._service_batch_get_assets_history_async.py | 52 + ...t_service_batch_get_assets_history_sync.py | 52 + ..._batch_get_effective_iam_policies_async.py | 53 + ...e_batch_get_effective_iam_policies_sync.py | 53 + ...nerated_asset_service_create_feed_async.py | 57 + ...enerated_asset_service_create_feed_sync.py | 57 + ..._asset_service_create_saved_query_async.py | 53 + ...d_asset_service_create_saved_query_sync.py | 53 + ...nerated_asset_service_delete_feed_async.py | 50 + ...enerated_asset_service_delete_feed_sync.py | 50 + ..._asset_service_delete_saved_query_async.py | 50 + ...d_asset_service_delete_saved_query_sync.py | 50 + ...rated_asset_service_export_assets_async.py | 60 + ...erated_asset_service_export_assets_sync.py | 60 + ..._generated_asset_service_get_feed_async.py | 52 + ...1_generated_asset_service_get_feed_sync.py | 52 + ...ted_asset_service_get_saved_query_async.py | 52 + ...ated_asset_service_get_saved_query_sync.py | 52 + ...nerated_asset_service_list_assets_async.py | 53 + ...enerated_asset_service_list_assets_sync.py | 53 + ...enerated_asset_service_list_feeds_async.py | 52 + ...generated_asset_service_list_feeds_sync.py | 52 + ..._asset_service_list_saved_queries_async.py | 53 + ...d_asset_service_list_saved_queries_sync.py | 53 + ...erated_asset_service_query_assets_async.py | 53 + ...nerated_asset_service_query_assets_sync.py | 53 + ...t_service_search_all_iam_policies_async.py | 53 + ...et_service_search_all_iam_policies_sync.py | 53 + ...sset_service_search_all_resources_async.py | 53 + ...asset_service_search_all_resources_sync.py | 53 + ...nerated_asset_service_update_feed_async.py | 55 + ...enerated_asset_service_update_feed_sync.py | 55 + ..._asset_service_update_saved_query_async.py | 51 + ...d_asset_service_update_saved_query_sync.py | 51 + ...nippet_metadata_google.cloud.asset.v1.json | 3746 +++++ .../v1/scripts/fixup_asset_v1_keywords.py | 198 + 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 + .../v1/tests/unit/gapic/asset_v1/__init__.py | 16 + .../unit/gapic/asset_v1/test_asset_service.py | 13601 ++++++++++++++++ owl-bot-staging/v1p1beta1/.coveragerc | 13 + owl-bot-staging/v1p1beta1/.flake8 | 33 + owl-bot-staging/v1p1beta1/MANIFEST.in | 2 + owl-bot-staging/v1p1beta1/README.rst | 49 + .../v1p1beta1/docs/_static/custom.css | 3 + .../docs/asset_v1p1beta1/asset_service.rst | 10 + .../docs/asset_v1p1beta1/services.rst | 6 + .../v1p1beta1/docs/asset_v1p1beta1/types.rst | 6 + owl-bot-staging/v1p1beta1/docs/conf.py | 376 + owl-bot-staging/v1p1beta1/docs/index.rst | 7 + .../v1p1beta1/google/cloud/asset/__init__.py | 41 + .../google/cloud/asset/gapic_version.py | 16 + .../v1p1beta1/google/cloud/asset/py.typed | 2 + .../google/cloud/asset_v1p1beta1/__init__.py | 42 + .../cloud/asset_v1p1beta1/gapic_metadata.json | 58 + .../cloud/asset_v1p1beta1/gapic_version.py | 16 + .../google/cloud/asset_v1p1beta1/py.typed | 2 + .../asset_v1p1beta1/services/__init__.py | 15 + .../services/asset_service/__init__.py | 22 + .../services/asset_service/async_client.py | 494 + .../services/asset_service/client.py | 679 + .../services/asset_service/pagers.py | 261 + .../asset_service/transports/__init__.py | 38 + .../services/asset_service/transports/base.py | 177 + .../services/asset_service/transports/grpc.py | 303 + .../asset_service/transports/grpc_asyncio.py | 302 + .../services/asset_service/transports/rest.py | 399 + .../cloud/asset_v1p1beta1/types/__init__.py | 36 + .../asset_v1p1beta1/types/asset_service.py | 212 + .../cloud/asset_v1p1beta1/types/assets.py | 203 + owl-bot-staging/v1p1beta1/mypy.ini | 3 + owl-bot-staging/v1p1beta1/noxfile.py | 184 + ...t_service_search_all_iam_policies_async.py | 53 + ...et_service_search_all_iam_policies_sync.py | 53 + ...sset_service_search_all_resources_async.py | 53 + ...asset_service_search_all_resources_sync.py | 53 + ...metadata_google.cloud.asset.v1p1beta1.json | 361 + .../scripts/fixup_asset_v1p1beta1_keywords.py | 177 + owl-bot-staging/v1p1beta1/setup.py | 91 + .../v1p1beta1/testing/constraints-3.10.txt | 7 + .../v1p1beta1/testing/constraints-3.11.txt | 7 + .../v1p1beta1/testing/constraints-3.12.txt | 7 + .../v1p1beta1/testing/constraints-3.7.txt | 10 + .../v1p1beta1/testing/constraints-3.8.txt | 7 + .../v1p1beta1/testing/constraints-3.9.txt | 7 + owl-bot-staging/v1p1beta1/tests/__init__.py | 16 + .../v1p1beta1/tests/unit/__init__.py | 16 + .../v1p1beta1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/asset_v1p1beta1/__init__.py | 16 + .../asset_v1p1beta1/test_asset_service.py | 2674 +++ owl-bot-staging/v1p2beta1/.coveragerc | 13 + owl-bot-staging/v1p2beta1/.flake8 | 33 + owl-bot-staging/v1p2beta1/MANIFEST.in | 2 + owl-bot-staging/v1p2beta1/README.rst | 49 + .../v1p2beta1/docs/_static/custom.css | 3 + .../docs/asset_v1p2beta1/asset_service.rst | 6 + .../docs/asset_v1p2beta1/services.rst | 6 + .../v1p2beta1/docs/asset_v1p2beta1/types.rst | 6 + owl-bot-staging/v1p2beta1/docs/conf.py | 376 + owl-bot-staging/v1p2beta1/docs/index.rst | 7 + .../v1p2beta1/google/cloud/asset/__init__.py | 59 + .../google/cloud/asset/gapic_version.py | 16 + .../v1p2beta1/google/cloud/asset/py.typed | 2 + .../google/cloud/asset_v1p2beta1/__init__.py | 60 + .../cloud/asset_v1p2beta1/gapic_metadata.json | 103 + .../cloud/asset_v1p2beta1/gapic_version.py | 16 + .../google/cloud/asset_v1p2beta1/py.typed | 2 + .../asset_v1p2beta1/services/__init__.py | 15 + .../services/asset_service/__init__.py | 22 + .../services/asset_service/async_client.py | 751 + .../services/asset_service/client.py | 934 ++ .../asset_service/transports/__init__.py | 38 + .../services/asset_service/transports/base.py | 226 + .../services/asset_service/transports/grpc.py | 372 + .../asset_service/transports/grpc_asyncio.py | 371 + .../services/asset_service/transports/rest.py | 747 + .../cloud/asset_v1p2beta1/types/__init__.py | 54 + .../asset_v1p2beta1/types/asset_service.py | 346 + .../cloud/asset_v1p2beta1/types/assets.py | 218 + owl-bot-staging/v1p2beta1/mypy.ini | 3 + owl-bot-staging/v1p2beta1/noxfile.py | 184 + ...nerated_asset_service_create_feed_async.py | 57 + ...enerated_asset_service_create_feed_sync.py | 57 + ...nerated_asset_service_delete_feed_async.py | 50 + ...enerated_asset_service_delete_feed_sync.py | 50 + ..._generated_asset_service_get_feed_async.py | 52 + ...1_generated_asset_service_get_feed_sync.py | 52 + ...enerated_asset_service_list_feeds_async.py | 52 + ...generated_asset_service_list_feeds_sync.py | 52 + ...nerated_asset_service_update_feed_async.py | 55 + ...enerated_asset_service_update_feed_sync.py | 55 + ...metadata_google.cloud.asset.v1p2beta1.json | 814 + .../scripts/fixup_asset_v1p2beta1_keywords.py | 180 + owl-bot-staging/v1p2beta1/setup.py | 91 + .../v1p2beta1/testing/constraints-3.10.txt | 7 + .../v1p2beta1/testing/constraints-3.11.txt | 7 + .../v1p2beta1/testing/constraints-3.12.txt | 7 + .../v1p2beta1/testing/constraints-3.7.txt | 10 + .../v1p2beta1/testing/constraints-3.8.txt | 7 + .../v1p2beta1/testing/constraints-3.9.txt | 7 + owl-bot-staging/v1p2beta1/tests/__init__.py | 16 + .../v1p2beta1/tests/unit/__init__.py | 16 + .../v1p2beta1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/asset_v1p2beta1/__init__.py | 16 + .../asset_v1p2beta1/test_asset_service.py | 3600 ++++ owl-bot-staging/v1p5beta1/.coveragerc | 13 + owl-bot-staging/v1p5beta1/.flake8 | 33 + owl-bot-staging/v1p5beta1/MANIFEST.in | 2 + owl-bot-staging/v1p5beta1/README.rst | 49 + .../v1p5beta1/docs/_static/custom.css | 3 + .../docs/asset_v1p5beta1/asset_service.rst | 10 + .../docs/asset_v1p5beta1/services.rst | 6 + .../v1p5beta1/docs/asset_v1p5beta1/types.rst | 6 + owl-bot-staging/v1p5beta1/docs/conf.py | 376 + owl-bot-staging/v1p5beta1/docs/index.rst | 7 + .../v1p5beta1/google/cloud/asset/__init__.py | 37 + .../google/cloud/asset/gapic_version.py | 16 + .../v1p5beta1/google/cloud/asset/py.typed | 2 + .../google/cloud/asset_v1p5beta1/__init__.py | 38 + .../cloud/asset_v1p5beta1/gapic_metadata.json | 43 + .../cloud/asset_v1p5beta1/gapic_version.py | 16 + .../google/cloud/asset_v1p5beta1/py.typed | 2 + .../asset_v1p5beta1/services/__init__.py | 15 + .../services/asset_service/__init__.py | 22 + .../services/asset_service/async_client.py | 330 + .../services/asset_service/client.py | 558 + .../services/asset_service/pagers.py | 140 + .../asset_service/transports/__init__.py | 38 + .../services/asset_service/transports/base.py | 156 + .../services/asset_service/transports/grpc.py | 266 + .../asset_service/transports/grpc_asyncio.py | 265 + .../services/asset_service/transports/rest.py | 289 + .../cloud/asset_v1p5beta1/types/__init__.py | 32 + .../asset_v1p5beta1/types/asset_service.py | 179 + .../cloud/asset_v1p5beta1/types/assets.py | 235 + owl-bot-staging/v1p5beta1/mypy.ini | 3 + owl-bot-staging/v1p5beta1/noxfile.py | 184 + ...nerated_asset_service_list_assets_async.py | 53 + ...enerated_asset_service_list_assets_sync.py | 53 + ...metadata_google.cloud.asset.v1p5beta1.json | 176 + .../scripts/fixup_asset_v1p5beta1_keywords.py | 176 + owl-bot-staging/v1p5beta1/setup.py | 91 + .../v1p5beta1/testing/constraints-3.10.txt | 7 + .../v1p5beta1/testing/constraints-3.11.txt | 7 + .../v1p5beta1/testing/constraints-3.12.txt | 7 + .../v1p5beta1/testing/constraints-3.7.txt | 10 + .../v1p5beta1/testing/constraints-3.8.txt | 7 + .../v1p5beta1/testing/constraints-3.9.txt | 7 + owl-bot-staging/v1p5beta1/tests/__init__.py | 16 + .../v1p5beta1/tests/unit/__init__.py | 16 + .../v1p5beta1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/asset_v1p5beta1/__init__.py | 16 + .../asset_v1p5beta1/test_asset_service.py | 1988 +++ 245 files changed, 64438 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/_static/custom.css create mode 100644 owl-bot-staging/v1/docs/asset_v1/asset_service.rst create mode 100644 owl-bot-staging/v1/docs/asset_v1/services.rst create mode 100644 owl-bot-staging/v1/docs/asset_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/asset/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/asset/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/asset/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/py.typed create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py create mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/types/assets.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/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py create mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json create mode 100644 owl-bot-staging/v1/scripts/fixup_asset_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/asset_v1/__init__.py create mode 100644 owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py create mode 100644 owl-bot-staging/v1p1beta1/.coveragerc create mode 100644 owl-bot-staging/v1p1beta1/.flake8 create mode 100644 owl-bot-staging/v1p1beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p1beta1/README.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst create mode 100644 owl-bot-staging/v1p1beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p1beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py create mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py create mode 100644 owl-bot-staging/v1p1beta1/mypy.ini create mode 100644 owl-bot-staging/v1p1beta1/noxfile.py create mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py create mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py create mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py create mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py create mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json create mode 100644 owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py create mode 100644 owl-bot-staging/v1p1beta1/setup.py create mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1p1beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py create mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py create mode 100644 owl-bot-staging/v1p2beta1/.coveragerc create mode 100644 owl-bot-staging/v1p2beta1/.flake8 create mode 100644 owl-bot-staging/v1p2beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p2beta1/README.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst create mode 100644 owl-bot-staging/v1p2beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p2beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py create mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py create mode 100644 owl-bot-staging/v1p2beta1/mypy.ini create mode 100644 owl-bot-staging/v1p2beta1/noxfile.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py create mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json create mode 100644 owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py create mode 100644 owl-bot-staging/v1p2beta1/setup.py create mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1p2beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py create mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py create mode 100644 owl-bot-staging/v1p5beta1/.coveragerc create mode 100644 owl-bot-staging/v1p5beta1/.flake8 create mode 100644 owl-bot-staging/v1p5beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p5beta1/README.rst create mode 100644 owl-bot-staging/v1p5beta1/docs/_static/custom.css create mode 100644 owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst create mode 100644 owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst create mode 100644 owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst create mode 100644 owl-bot-staging/v1p5beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p5beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py create mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py create mode 100644 owl-bot-staging/v1p5beta1/mypy.ini create mode 100644 owl-bot-staging/v1p5beta1/noxfile.py create mode 100644 owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py create mode 100644 owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py create mode 100644 owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json create mode 100644 owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py create mode 100644 owl-bot-staging/v1p5beta1/setup.py create mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/v1p5beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py create mode 100644 owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc new file mode 100644 index 00000000..801f6d8a --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py + google/cloud/asset/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 00000000..29227d4c --- /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 00000000..5c97e276 --- /dev/null +++ b/owl-bot-staging/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/asset *.py +recursive-include google/cloud/asset_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst new file mode 100644 index 00000000..110d4086 --- /dev/null +++ b/owl-bot-staging/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Asset 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 Asset 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/_static/custom.css b/owl-bot-staging/v1/docs/_static/custom.css new file mode 100644 index 00000000..06423be0 --- /dev/null +++ b/owl-bot-staging/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1/docs/asset_v1/asset_service.rst b/owl-bot-staging/v1/docs/asset_v1/asset_service.rst new file mode 100644 index 00000000..b2f80a4b --- /dev/null +++ b/owl-bot-staging/v1/docs/asset_v1/asset_service.rst @@ -0,0 +1,10 @@ +AssetService +------------------------------ + +.. automodule:: google.cloud.asset_v1.services.asset_service + :members: + :inherited-members: + +.. automodule:: google.cloud.asset_v1.services.asset_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1/docs/asset_v1/services.rst b/owl-bot-staging/v1/docs/asset_v1/services.rst new file mode 100644 index 00000000..a5ddb91f --- /dev/null +++ b/owl-bot-staging/v1/docs/asset_v1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1 API +====================================== +.. toctree:: + :maxdepth: 2 + + asset_service diff --git a/owl-bot-staging/v1/docs/asset_v1/types.rst b/owl-bot-staging/v1/docs/asset_v1/types.rst new file mode 100644 index 00000000..750d9c16 --- /dev/null +++ b/owl-bot-staging/v1/docs/asset_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Asset v1 API +=================================== + +.. automodule:: google.cloud.asset_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 00000000..b6b4f094 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-asset 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-asset" +copyright = u"2023, 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 = 'en' + +# 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-asset-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-asset.tex", + u"google-cloud-asset 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-asset", + u"Google Cloud Asset 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-asset", + u"google-cloud-asset Documentation", + author, + "google-cloud-asset", + "GAPIC library for Google Cloud Asset 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 00000000..fee6608e --- /dev/null +++ b/owl-bot-staging/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + asset_v1/services + asset_v1/types diff --git a/owl-bot-staging/v1/google/cloud/asset/__init__.py b/owl-bot-staging/v1/google/cloud/asset/__init__.py new file mode 100644 index 00000000..40c78b1c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset/__init__.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.asset_v1.services.asset_service.client import AssetServiceClient +from google.cloud.asset_v1.services.asset_service.async_client import AssetServiceAsyncClient + +from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyLongrunningMetadata +from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyLongrunningRequest +from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyLongrunningResponse +from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyRequest +from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyResponse +from google.cloud.asset_v1.types.asset_service import AnalyzeMoveRequest +from google.cloud.asset_v1.types.asset_service import AnalyzeMoveResponse +from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPoliciesRequest +from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPoliciesResponse +from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedAssetsRequest +from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedAssetsResponse +from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedContainersRequest +from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedContainersResponse +from google.cloud.asset_v1.types.asset_service import AnalyzerOrgPolicy +from google.cloud.asset_v1.types.asset_service import AnalyzerOrgPolicyConstraint +from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryRequest +from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryResponse +from google.cloud.asset_v1.types.asset_service import BatchGetEffectiveIamPoliciesRequest +from google.cloud.asset_v1.types.asset_service import BatchGetEffectiveIamPoliciesResponse +from google.cloud.asset_v1.types.asset_service import BigQueryDestination +from google.cloud.asset_v1.types.asset_service import CreateFeedRequest +from google.cloud.asset_v1.types.asset_service import CreateSavedQueryRequest +from google.cloud.asset_v1.types.asset_service import DeleteFeedRequest +from google.cloud.asset_v1.types.asset_service import DeleteSavedQueryRequest +from google.cloud.asset_v1.types.asset_service import ExportAssetsRequest +from google.cloud.asset_v1.types.asset_service import ExportAssetsResponse +from google.cloud.asset_v1.types.asset_service import Feed +from google.cloud.asset_v1.types.asset_service import FeedOutputConfig +from google.cloud.asset_v1.types.asset_service import GcsDestination +from google.cloud.asset_v1.types.asset_service import GcsOutputResult +from google.cloud.asset_v1.types.asset_service import GetFeedRequest +from google.cloud.asset_v1.types.asset_service import GetSavedQueryRequest +from google.cloud.asset_v1.types.asset_service import IamPolicyAnalysisOutputConfig +from google.cloud.asset_v1.types.asset_service import IamPolicyAnalysisQuery +from google.cloud.asset_v1.types.asset_service import ListAssetsRequest +from google.cloud.asset_v1.types.asset_service import ListAssetsResponse +from google.cloud.asset_v1.types.asset_service import ListFeedsRequest +from google.cloud.asset_v1.types.asset_service import ListFeedsResponse +from google.cloud.asset_v1.types.asset_service import ListSavedQueriesRequest +from google.cloud.asset_v1.types.asset_service import ListSavedQueriesResponse +from google.cloud.asset_v1.types.asset_service import MoveAnalysis +from google.cloud.asset_v1.types.asset_service import MoveAnalysisResult +from google.cloud.asset_v1.types.asset_service import MoveImpact +from google.cloud.asset_v1.types.asset_service import OutputConfig +from google.cloud.asset_v1.types.asset_service import OutputResult +from google.cloud.asset_v1.types.asset_service import PartitionSpec +from google.cloud.asset_v1.types.asset_service import PubsubDestination +from google.cloud.asset_v1.types.asset_service import QueryAssetsOutputConfig +from google.cloud.asset_v1.types.asset_service import QueryAssetsRequest +from google.cloud.asset_v1.types.asset_service import QueryAssetsResponse +from google.cloud.asset_v1.types.asset_service import QueryResult +from google.cloud.asset_v1.types.asset_service import SavedQuery +from google.cloud.asset_v1.types.asset_service import SearchAllIamPoliciesRequest +from google.cloud.asset_v1.types.asset_service import SearchAllIamPoliciesResponse +from google.cloud.asset_v1.types.asset_service import SearchAllResourcesRequest +from google.cloud.asset_v1.types.asset_service import SearchAllResourcesResponse +from google.cloud.asset_v1.types.asset_service import TableFieldSchema +from google.cloud.asset_v1.types.asset_service import TableSchema +from google.cloud.asset_v1.types.asset_service import UpdateFeedRequest +from google.cloud.asset_v1.types.asset_service import UpdateSavedQueryRequest +from google.cloud.asset_v1.types.asset_service import ContentType +from google.cloud.asset_v1.types.assets import Asset +from google.cloud.asset_v1.types.assets import AttachedResource +from google.cloud.asset_v1.types.assets import ConditionEvaluation +from google.cloud.asset_v1.types.assets import EffectiveTagDetails +from google.cloud.asset_v1.types.assets import IamPolicyAnalysisResult +from google.cloud.asset_v1.types.assets import IamPolicyAnalysisState +from google.cloud.asset_v1.types.assets import IamPolicySearchResult +from google.cloud.asset_v1.types.assets import RelatedAsset +from google.cloud.asset_v1.types.assets import RelatedAssets +from google.cloud.asset_v1.types.assets import RelatedResource +from google.cloud.asset_v1.types.assets import RelatedResources +from google.cloud.asset_v1.types.assets import RelationshipAttributes +from google.cloud.asset_v1.types.assets import Resource +from google.cloud.asset_v1.types.assets import ResourceSearchResult +from google.cloud.asset_v1.types.assets import Tag +from google.cloud.asset_v1.types.assets import TemporalAsset +from google.cloud.asset_v1.types.assets import TimeWindow +from google.cloud.asset_v1.types.assets import VersionedResource + +__all__ = ('AssetServiceClient', + 'AssetServiceAsyncClient', + 'AnalyzeIamPolicyLongrunningMetadata', + 'AnalyzeIamPolicyLongrunningRequest', + 'AnalyzeIamPolicyLongrunningResponse', + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'AnalyzeMoveRequest', + 'AnalyzeMoveResponse', + 'AnalyzeOrgPoliciesRequest', + 'AnalyzeOrgPoliciesResponse', + 'AnalyzeOrgPolicyGovernedAssetsRequest', + 'AnalyzeOrgPolicyGovernedAssetsResponse', + 'AnalyzeOrgPolicyGovernedContainersRequest', + 'AnalyzeOrgPolicyGovernedContainersResponse', + 'AnalyzerOrgPolicy', + 'AnalyzerOrgPolicyConstraint', + 'BatchGetAssetsHistoryRequest', + 'BatchGetAssetsHistoryResponse', + 'BatchGetEffectiveIamPoliciesRequest', + 'BatchGetEffectiveIamPoliciesResponse', + 'BigQueryDestination', + 'CreateFeedRequest', + 'CreateSavedQueryRequest', + 'DeleteFeedRequest', + 'DeleteSavedQueryRequest', + 'ExportAssetsRequest', + 'ExportAssetsResponse', + 'Feed', + 'FeedOutputConfig', + 'GcsDestination', + 'GcsOutputResult', + 'GetFeedRequest', + 'GetSavedQueryRequest', + 'IamPolicyAnalysisOutputConfig', + 'IamPolicyAnalysisQuery', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'ListSavedQueriesRequest', + 'ListSavedQueriesResponse', + 'MoveAnalysis', + 'MoveAnalysisResult', + 'MoveImpact', + 'OutputConfig', + 'OutputResult', + 'PartitionSpec', + 'PubsubDestination', + 'QueryAssetsOutputConfig', + 'QueryAssetsRequest', + 'QueryAssetsResponse', + 'QueryResult', + 'SavedQuery', + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'TableFieldSchema', + 'TableSchema', + 'UpdateFeedRequest', + 'UpdateSavedQueryRequest', + 'ContentType', + 'Asset', + 'AttachedResource', + 'ConditionEvaluation', + 'EffectiveTagDetails', + 'IamPolicyAnalysisResult', + 'IamPolicyAnalysisState', + 'IamPolicySearchResult', + 'RelatedAsset', + 'RelatedAssets', + 'RelatedResource', + 'RelatedResources', + 'RelationshipAttributes', + 'Resource', + 'ResourceSearchResult', + 'Tag', + 'TemporalAsset', + 'TimeWindow', + 'VersionedResource', +) diff --git a/owl-bot-staging/v1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1/google/cloud/asset/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/asset/py.typed b/owl-bot-staging/v1/google/cloud/asset/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py new file mode 100644 index 00000000..98cd9a11 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py @@ -0,0 +1,186 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + +from .types.asset_service import AnalyzeIamPolicyLongrunningMetadata +from .types.asset_service import AnalyzeIamPolicyLongrunningRequest +from .types.asset_service import AnalyzeIamPolicyLongrunningResponse +from .types.asset_service import AnalyzeIamPolicyRequest +from .types.asset_service import AnalyzeIamPolicyResponse +from .types.asset_service import AnalyzeMoveRequest +from .types.asset_service import AnalyzeMoveResponse +from .types.asset_service import AnalyzeOrgPoliciesRequest +from .types.asset_service import AnalyzeOrgPoliciesResponse +from .types.asset_service import AnalyzeOrgPolicyGovernedAssetsRequest +from .types.asset_service import AnalyzeOrgPolicyGovernedAssetsResponse +from .types.asset_service import AnalyzeOrgPolicyGovernedContainersRequest +from .types.asset_service import AnalyzeOrgPolicyGovernedContainersResponse +from .types.asset_service import AnalyzerOrgPolicy +from .types.asset_service import AnalyzerOrgPolicyConstraint +from .types.asset_service import BatchGetAssetsHistoryRequest +from .types.asset_service import BatchGetAssetsHistoryResponse +from .types.asset_service import BatchGetEffectiveIamPoliciesRequest +from .types.asset_service import BatchGetEffectiveIamPoliciesResponse +from .types.asset_service import BigQueryDestination +from .types.asset_service import CreateFeedRequest +from .types.asset_service import CreateSavedQueryRequest +from .types.asset_service import DeleteFeedRequest +from .types.asset_service import DeleteSavedQueryRequest +from .types.asset_service import ExportAssetsRequest +from .types.asset_service import ExportAssetsResponse +from .types.asset_service import Feed +from .types.asset_service import FeedOutputConfig +from .types.asset_service import GcsDestination +from .types.asset_service import GcsOutputResult +from .types.asset_service import GetFeedRequest +from .types.asset_service import GetSavedQueryRequest +from .types.asset_service import IamPolicyAnalysisOutputConfig +from .types.asset_service import IamPolicyAnalysisQuery +from .types.asset_service import ListAssetsRequest +from .types.asset_service import ListAssetsResponse +from .types.asset_service import ListFeedsRequest +from .types.asset_service import ListFeedsResponse +from .types.asset_service import ListSavedQueriesRequest +from .types.asset_service import ListSavedQueriesResponse +from .types.asset_service import MoveAnalysis +from .types.asset_service import MoveAnalysisResult +from .types.asset_service import MoveImpact +from .types.asset_service import OutputConfig +from .types.asset_service import OutputResult +from .types.asset_service import PartitionSpec +from .types.asset_service import PubsubDestination +from .types.asset_service import QueryAssetsOutputConfig +from .types.asset_service import QueryAssetsRequest +from .types.asset_service import QueryAssetsResponse +from .types.asset_service import QueryResult +from .types.asset_service import SavedQuery +from .types.asset_service import SearchAllIamPoliciesRequest +from .types.asset_service import SearchAllIamPoliciesResponse +from .types.asset_service import SearchAllResourcesRequest +from .types.asset_service import SearchAllResourcesResponse +from .types.asset_service import TableFieldSchema +from .types.asset_service import TableSchema +from .types.asset_service import UpdateFeedRequest +from .types.asset_service import UpdateSavedQueryRequest +from .types.asset_service import ContentType +from .types.assets import Asset +from .types.assets import AttachedResource +from .types.assets import ConditionEvaluation +from .types.assets import EffectiveTagDetails +from .types.assets import IamPolicyAnalysisResult +from .types.assets import IamPolicyAnalysisState +from .types.assets import IamPolicySearchResult +from .types.assets import RelatedAsset +from .types.assets import RelatedAssets +from .types.assets import RelatedResource +from .types.assets import RelatedResources +from .types.assets import RelationshipAttributes +from .types.assets import Resource +from .types.assets import ResourceSearchResult +from .types.assets import Tag +from .types.assets import TemporalAsset +from .types.assets import TimeWindow +from .types.assets import VersionedResource + +__all__ = ( + 'AssetServiceAsyncClient', +'AnalyzeIamPolicyLongrunningMetadata', +'AnalyzeIamPolicyLongrunningRequest', +'AnalyzeIamPolicyLongrunningResponse', +'AnalyzeIamPolicyRequest', +'AnalyzeIamPolicyResponse', +'AnalyzeMoveRequest', +'AnalyzeMoveResponse', +'AnalyzeOrgPoliciesRequest', +'AnalyzeOrgPoliciesResponse', +'AnalyzeOrgPolicyGovernedAssetsRequest', +'AnalyzeOrgPolicyGovernedAssetsResponse', +'AnalyzeOrgPolicyGovernedContainersRequest', +'AnalyzeOrgPolicyGovernedContainersResponse', +'AnalyzerOrgPolicy', +'AnalyzerOrgPolicyConstraint', +'Asset', +'AssetServiceClient', +'AttachedResource', +'BatchGetAssetsHistoryRequest', +'BatchGetAssetsHistoryResponse', +'BatchGetEffectiveIamPoliciesRequest', +'BatchGetEffectiveIamPoliciesResponse', +'BigQueryDestination', +'ConditionEvaluation', +'ContentType', +'CreateFeedRequest', +'CreateSavedQueryRequest', +'DeleteFeedRequest', +'DeleteSavedQueryRequest', +'EffectiveTagDetails', +'ExportAssetsRequest', +'ExportAssetsResponse', +'Feed', +'FeedOutputConfig', +'GcsDestination', +'GcsOutputResult', +'GetFeedRequest', +'GetSavedQueryRequest', +'IamPolicyAnalysisOutputConfig', +'IamPolicyAnalysisQuery', +'IamPolicyAnalysisResult', +'IamPolicyAnalysisState', +'IamPolicySearchResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFeedsRequest', +'ListFeedsResponse', +'ListSavedQueriesRequest', +'ListSavedQueriesResponse', +'MoveAnalysis', +'MoveAnalysisResult', +'MoveImpact', +'OutputConfig', +'OutputResult', +'PartitionSpec', +'PubsubDestination', +'QueryAssetsOutputConfig', +'QueryAssetsRequest', +'QueryAssetsResponse', +'QueryResult', +'RelatedAsset', +'RelatedAssets', +'RelatedResource', +'RelatedResources', +'RelationshipAttributes', +'Resource', +'ResourceSearchResult', +'SavedQuery', +'SearchAllIamPoliciesRequest', +'SearchAllIamPoliciesResponse', +'SearchAllResourcesRequest', +'SearchAllResourcesResponse', +'TableFieldSchema', +'TableSchema', +'Tag', +'TemporalAsset', +'TimeWindow', +'UpdateFeedRequest', +'UpdateSavedQueryRequest', +'VersionedResource', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json new file mode 100644 index 00000000..e39e5043 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json @@ -0,0 +1,373 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1", + "protoPackage": "google.cloud.asset.v1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "AnalyzeIamPolicyLongrunning": { + "methods": [ + "analyze_iam_policy_longrunning" + ] + }, + "AnalyzeMove": { + "methods": [ + "analyze_move" + ] + }, + "AnalyzeOrgPolicies": { + "methods": [ + "analyze_org_policies" + ] + }, + "AnalyzeOrgPolicyGovernedAssets": { + "methods": [ + "analyze_org_policy_governed_assets" + ] + }, + "AnalyzeOrgPolicyGovernedContainers": { + "methods": [ + "analyze_org_policy_governed_containers" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "batch_get_assets_history" + ] + }, + "BatchGetEffectiveIamPolicies": { + "methods": [ + "batch_get_effective_iam_policies" + ] + }, + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "CreateSavedQuery": { + "methods": [ + "create_saved_query" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "DeleteSavedQuery": { + "methods": [ + "delete_saved_query" + ] + }, + "ExportAssets": { + "methods": [ + "export_assets" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "GetSavedQuery": { + "methods": [ + "get_saved_query" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "ListSavedQueries": { + "methods": [ + "list_saved_queries" + ] + }, + "QueryAssets": { + "methods": [ + "query_assets" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + }, + "UpdateSavedQuery": { + "methods": [ + "update_saved_query" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "AnalyzeIamPolicyLongrunning": { + "methods": [ + "analyze_iam_policy_longrunning" + ] + }, + "AnalyzeMove": { + "methods": [ + "analyze_move" + ] + }, + "AnalyzeOrgPolicies": { + "methods": [ + "analyze_org_policies" + ] + }, + "AnalyzeOrgPolicyGovernedAssets": { + "methods": [ + "analyze_org_policy_governed_assets" + ] + }, + "AnalyzeOrgPolicyGovernedContainers": { + "methods": [ + "analyze_org_policy_governed_containers" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "batch_get_assets_history" + ] + }, + "BatchGetEffectiveIamPolicies": { + "methods": [ + "batch_get_effective_iam_policies" + ] + }, + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "CreateSavedQuery": { + "methods": [ + "create_saved_query" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "DeleteSavedQuery": { + "methods": [ + "delete_saved_query" + ] + }, + "ExportAssets": { + "methods": [ + "export_assets" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "GetSavedQuery": { + "methods": [ + "get_saved_query" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "ListSavedQueries": { + "methods": [ + "list_saved_queries" + ] + }, + "QueryAssets": { + "methods": [ + "query_assets" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + }, + "UpdateSavedQuery": { + "methods": [ + "update_saved_query" + ] + } + } + }, + "rest": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "AnalyzeIamPolicyLongrunning": { + "methods": [ + "analyze_iam_policy_longrunning" + ] + }, + "AnalyzeMove": { + "methods": [ + "analyze_move" + ] + }, + "AnalyzeOrgPolicies": { + "methods": [ + "analyze_org_policies" + ] + }, + "AnalyzeOrgPolicyGovernedAssets": { + "methods": [ + "analyze_org_policy_governed_assets" + ] + }, + "AnalyzeOrgPolicyGovernedContainers": { + "methods": [ + "analyze_org_policy_governed_containers" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "batch_get_assets_history" + ] + }, + "BatchGetEffectiveIamPolicies": { + "methods": [ + "batch_get_effective_iam_policies" + ] + }, + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "CreateSavedQuery": { + "methods": [ + "create_saved_query" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "DeleteSavedQuery": { + "methods": [ + "delete_saved_query" + ] + }, + "ExportAssets": { + "methods": [ + "export_assets" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "GetSavedQuery": { + "methods": [ + "get_saved_query" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "ListSavedQueries": { + "methods": [ + "list_saved_queries" + ] + }, + "QueryAssets": { + "methods": [ + "query_assets" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + }, + "UpdateSavedQuery": { + "methods": [ + "update_saved_query" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/py.typed b/owl-bot-staging/v1/google/cloud/asset_v1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py new file mode 100644 index 00000000..89a37dc9 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py new file mode 100644 index 00000000..542f923f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient + +__all__ = ( + 'AssetServiceClient', + 'AssetServiceAsyncClient', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py new file mode 100644 index 00000000..58f650d9 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py @@ -0,0 +1,3169 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.asset_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.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + access_level_path = staticmethod(AssetServiceClient.access_level_path) + parse_access_level_path = staticmethod(AssetServiceClient.parse_access_level_path) + access_policy_path = staticmethod(AssetServiceClient.access_policy_path) + parse_access_policy_path = staticmethod(AssetServiceClient.parse_access_policy_path) + asset_path = staticmethod(AssetServiceClient.asset_path) + parse_asset_path = staticmethod(AssetServiceClient.parse_asset_path) + feed_path = staticmethod(AssetServiceClient.feed_path) + parse_feed_path = staticmethod(AssetServiceClient.parse_feed_path) + inventory_path = staticmethod(AssetServiceClient.inventory_path) + parse_inventory_path = staticmethod(AssetServiceClient.parse_inventory_path) + saved_query_path = staticmethod(AssetServiceClient.saved_query_path) + parse_saved_query_path = staticmethod(AssetServiceClient.parse_saved_query_path) + service_perimeter_path = staticmethod(AssetServiceClient.service_perimeter_path) + parse_service_perimeter_path = staticmethod(AssetServiceClient.parse_service_perimeter_path) + common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AssetServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AssetServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AssetServiceClient.common_project_path) + parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) + common_location_path = staticmethod(AssetServiceClient.common_location_path) + parse_common_location_path = staticmethod(AssetServiceClient.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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def export_assets(self, + request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset Protobuf as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] + API, which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + .. 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 asset_v1 + + async def sample_export_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + output_config = asset_v1.OutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.ExportAssetsRequest( + parent="parent_value", + output_config=output_config, + ) + + # Make the request + operation = client.export_assets(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.ExportAssetsRequest, dict]]): + The request object. Export asset request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.ExportAssetsResponse` The export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + request = asset_service.ExportAssetsRequest(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.export_assets, + 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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + asset_service.ExportAssetsResponse, + metadata_type=asset_service.ExportAssetsRequest, + ) + + # Done; return the response. + return response + + async def list_assets(self, + request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsAsyncPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + .. 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 asset_v1 + + async def sample_list_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.ListAssetsRequest, dict]]): + The request object. ListAssets request. + parent (:class:`str`): + Required. Name of the organization, folder, or project + the assets belong to. Format: + "organizations/[organization-number]" (such as + "organizations/123"), "projects/[project-id]" (such as + "projects/my-project-id"), "projects/[project-number]" + (such as "projects/12345"), or "folders/[folder-number]" + (such as "folders/12345"). + + 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.asset_v1.services.asset_service.pagers.ListAssetsAsyncPager: + ListAssets response. + + 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 = asset_service.ListAssetsRequest(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_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_get_assets_history(self, + request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: + r"""Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + .. 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 asset_v1 + + async def sample_batch_get_assets_history(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetAssetsHistoryRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_get_assets_history(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest, dict]]): + The request object. Batch get assets history request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.BatchGetAssetsHistoryResponse: + Batch get assets history response. + """ + # Create or coerce a protobuf request object. + request = asset_service.BatchGetAssetsHistoryRequest(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.batch_get_assets_history, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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 create_feed(self, + request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + .. 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 asset_v1 + + async def sample_create_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = await client.create_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.CreateFeedRequest, dict]]): + The request object. Create asset feed request. + parent (:class:`str`): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id"), or a + project number (such as + "projects/12345"). + + 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.asset_v1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + # 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 = asset_service.CreateFeedRequest(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.create_feed, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_feed(self, + request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + .. 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 asset_v1 + + async def sample_get_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = await client.get_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.GetFeedRequest, dict]]): + The request object. Get asset feed request. + name (:class:`str`): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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.asset_v1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + # 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 = asset_service.GetFeedRequest(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_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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_feeds(self, + request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + .. 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 asset_v1 + + async def sample_list_feeds(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_feeds(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.ListFeedsRequest, dict]]): + The request object. List asset feeds request. + parent (:class:`str`): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-id"). + + 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.asset_v1.types.ListFeedsResponse: + + """ + # 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 = asset_service.ListFeedsRequest(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_feeds, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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_feed(self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + .. 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 asset_v1 + + async def sample_update_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = await client.update_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.UpdateFeedRequest, dict]]): + The request object. Update asset feed request. + feed (:class:`google.cloud.asset_v1.types.Feed`): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + + This corresponds to the ``feed`` 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.asset_v1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + # 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([feed]) + 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 = asset_service.UpdateFeedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if feed is not None: + request.feed = feed + + # 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_feed, + 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(( + ("feed.name", request.feed.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_feed(self, + request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. + + .. 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 asset_v1 + + async def sample_delete_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + await client.delete_feed(request=request) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.DeleteFeedRequest, dict]]): + The request object. + name (:class:`str`): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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 = asset_service.DeleteFeedRequest(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_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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 search_all_resources(self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesAsyncPager: + r"""Searches all Google Cloud resources within the specified scope, + such as a project, folder, or organization. The caller must be + granted the ``cloudasset.assets.searchAllResources`` permission + on the desired scope, otherwise the request will be rejected. + + .. 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 asset_v1 + + async def sample_search_all_resources(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.SearchAllResourcesRequest, dict]]): + The request object. Search all resources request. + scope (:class:`str`): + Required. A scope can be a project, a folder, or an + organization. The search is limited to the resources + within the ``scope``. The caller must be granted the + ```cloudasset.assets.searchAllResources`` `__ + permission on the desired scope. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. See `how to construct a + query `__ + for more information. If not specified or empty, it will + search all the resources within the specified ``scope``. + + Examples: + + - ``name:Important`` to find Google Cloud resources + whose name contains ``Important`` as a word. + - ``name=Important`` to find the Google Cloud resource + whose name is exactly ``Important``. + - ``displayName:Impor*`` to find Google Cloud resources + whose display name contains ``Impor`` as a prefix of + any word in the field. + - ``location:us-west*`` to find Google Cloud resources + whose location contains both ``us`` and ``west`` as + prefixes. + - ``labels:prod`` to find Google Cloud resources whose + labels contain ``prod`` as a key or value. + - ``labels.env:prod`` to find Google Cloud resources + that have a label ``env`` and its value is ``prod``. + - ``labels.env:*`` to find Google Cloud resources that + have a label ``env``. + - ``tagKeys:env`` to find Google Cloud resources that + have directly attached tags where the + ```TagKey`` `__ + .\ ``namespacedName`` contains ``env``. + - ``tagValues:prod*`` to find Google Cloud resources + that have directly attached tags where the + ```TagValue`` `__ + .\ ``namespacedName`` contains a word prefixed by + ``prod``. + - ``tagValueIds=tagValues/123`` to find Google Cloud + resources that have directly attached tags where the + ```TagValue`` `__ + .\ ``name`` is exactly ``tagValues/123``. + - ``effectiveTagKeys:env`` to find Google Cloud + resources that have directly attached or inherited + tags where the + ```TagKey`` `__ + .\ ``namespacedName`` contains ``env``. + - ``effectiveTagValues:prod*`` to find Google Cloud + resources that have directly attached or inherited + tags where the + ```TagValue`` `__ + .\ ``namespacedName`` contains a word prefixed by + ``prod``. + - ``effectiveTagValueIds=tagValues/123`` to find Google + Cloud resources that have directly attached or + inherited tags where the + ```TagValue`` `__ + .\ ``name`` is exactly ``tagValues/123``. + - ``kmsKey:key`` to find Google Cloud resources + encrypted with a customer-managed encryption key + whose name contains ``key`` as a word. This field is + deprecated. Please use the ``kmsKeys`` field to + retrieve Cloud KMS key information. + - ``kmsKeys:key`` to find Google Cloud resources + encrypted with customer-managed encryption keys whose + name contains the word ``key``. + - ``relationships:instance-group-1`` to find Google + Cloud resources that have relationships with + ``instance-group-1`` in the related resource name. + - ``relationships:INSTANCE_TO_INSTANCEGROUP`` to find + Compute Engine instances that have relationships of + type ``INSTANCE_TO_INSTANCEGROUP``. + - ``relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1`` + to find Compute Engine instances that have + relationships with ``instance-group-1`` in the + Compute Engine instance group resource name, for + relationship type ``INSTANCE_TO_INSTANCEGROUP``. + - ``state:ACTIVE`` to find Google Cloud resources whose + state contains ``ACTIVE`` as a word. + - ``NOT state:ACTIVE`` to find Google Cloud resources + whose state doesn't contain ``ACTIVE`` as a word. + - ``createTime<1609459200`` to find Google Cloud + resources that were created before + ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the + epoch timestamp of ``2021-01-01 00:00:00 UTC`` in + seconds. + - ``updateTime>1609459200`` to find Google Cloud + resources that were updated after + ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the + epoch timestamp of ``2021-01-01 00:00:00 UTC`` in + seconds. + - ``Important`` to find Google Cloud resources that + contain ``Important`` as a word in any of the + searchable fields. + - ``Impor*`` to find Google Cloud resources that + contain ``Impor`` as a prefix of any word in any of + the searchable fields. + - ``Important location:(us-west1 OR global)`` to find + Google Cloud resources that contain ``Important`` as + a word in any of the searchable fields and are also + located in the ``us-west1`` region or the ``global`` + location. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (:class:`MutableSequence[str]`): + Optional. A list of asset types that this request + searches for. If empty, it will search all the + `searchable asset + types `__. + + Regular expressions are also supported. For example: + + - "compute.googleapis.com.*" snapshots resources whose + asset type starts with "compute.googleapis.com". + - ".*Instance" snapshots resources whose asset type + ends with "Instance". + - ".*Instance.*" snapshots resources whose asset type + contains "Instance". + + See `RE2 `__ + for all supported regular expression syntax. If the + regular expression does not match any supported asset + type, an INVALID_ARGUMENT error will be returned. + + This corresponds to the ``asset_types`` 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.asset_v1.services.asset_service.pagers.SearchAllResourcesAsyncPager: + Search all resources response. + + 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([scope, query, asset_types]) + 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 = asset_service.SearchAllResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types: + request.asset_types.extend(asset_types) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_resources, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.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(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllResourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_all_iam_policies(self, + request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesAsyncPager: + r"""Searches all IAM policies within the specified scope, such as a + project, folder, or organization. The caller must be granted the + ``cloudasset.assets.searchAllIamPolicies`` permission on the + desired scope, otherwise the request will be rejected. + + .. 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 asset_v1 + + async def sample_search_all_iam_policies(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.SearchAllIamPoliciesRequest, dict]]): + The request object. Search all IAM policies request. + scope (:class:`str`): + Required. A scope can be a project, a folder, or an + organization. The search is limited to the IAM policies + within the ``scope``. The caller must be granted the + ```cloudasset.assets.searchAllIamPolicies`` `__ + permission on the desired scope. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. See `how to construct a + query `__ + for more information. If not specified or empty, it will + search all the IAM policies within the specified + ``scope``. Note that the query string is compared + against each IAM policy binding, including its + principals, roles, and IAM conditions. The returned IAM + policies will only contain the bindings that match your + query. To learn more about the IAM policy structure, see + the `IAM policy + documentation `__. + + Examples: + + - ``policy:amy@gmail.com`` to find IAM policy bindings + that specify user "amy@gmail.com". + - ``policy:roles/compute.admin`` to find IAM policy + bindings that specify the Compute Admin role. + - ``policy:comp*`` to find IAM policy bindings that + contain "comp" as a prefix of any word in the + binding. + - ``policy.role.permissions:storage.buckets.update`` to + find IAM policy bindings that specify a role + containing "storage.buckets.update" permission. Note + that if callers don't have ``iam.roles.get`` access + to a role's included permissions, policy bindings + that specify this role will be dropped from the + search results. + - ``policy.role.permissions:upd*`` to find IAM policy + bindings that specify a role containing "upd" as a + prefix of any word in the role permission. Note that + if callers don't have ``iam.roles.get`` access to a + role's included permissions, policy bindings that + specify this role will be dropped from the search + results. + - ``resource:organizations/123456`` to find IAM policy + bindings that are set on "organizations/123456". + - ``resource=//cloudresourcemanager.googleapis.com/projects/myproject`` + to find IAM policy bindings that are set on the + project named "myproject". + - ``Important`` to find IAM policy bindings that + contain "Important" as a word in any of the + searchable fields (except for the included + permissions). + - ``resource:(instance1 OR instance2) policy:amy`` to + find IAM policy bindings that are set on resources + "instance1" or "instance2" and also specify user + "amy". + - ``roles:roles/compute.admin`` to find IAM policy + bindings that specify the Compute Admin role. + - ``memberTypes:user`` to find IAM policy bindings that + contain the principal type "user". + + This corresponds to the ``query`` 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.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager: + Search all IAM policies response. + + 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([scope, query]) + 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 = asset_service.SearchAllIamPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_iam_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.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(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllIamPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_iam_policy(self, + request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies to answer which identities have + what accesses on which resources. + + .. 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 asset_v1 + + async def sample_analyze_iam_policy(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + request = asset_v1.AnalyzeIamPolicyRequest( + analysis_query=analysis_query, + ) + + # Make the request + response = await client.analyze_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.AnalyzeIamPolicyRequest, dict]]): + The request object. A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.AnalyzeIamPolicyResponse: + A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + + """ + # Create or coerce a protobuf request object. + request = asset_service.AnalyzeIamPolicyRequest(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.analyze_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.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(( + ("analysis_query.scope", request.analysis_query.scope), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_iam_policy_longrunning(self, + request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Analyzes IAM policies asynchronously to answer which identities + have what accesses on which resources, and writes the analysis + results to a Google Cloud Storage or a BigQuery destination. For + Cloud Storage destination, the output format is the JSON format + that represents a + [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. + This method implements the + [google.longrunning.Operation][google.longrunning.Operation], + which allows you to track the operation status. We recommend + intervals of at least 2 seconds with exponential backoff retry + to poll the operation result. The metadata contains the metadata + for the long-running operation. + + .. 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 asset_v1 + + async def sample_analyze_iam_policy_longrunning(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + output_config = asset_v1.IamPolicyAnalysisOutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.AnalyzeIamPolicyLongrunningRequest( + analysis_query=analysis_query, + output_config=output_config, + ) + + # Make the request + operation = client.analyze_iam_policy_longrunning(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest, dict]]): + The request object. A request message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.AnalyzeIamPolicyLongrunningResponse` A response message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + + """ + # Create or coerce a protobuf request object. + request = asset_service.AnalyzeIamPolicyLongrunningRequest(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.analyze_iam_policy_longrunning, + 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(( + ("analysis_query.scope", request.analysis_query.scope), + )), + ) + + # 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, + asset_service.AnalyzeIamPolicyLongrunningResponse, + metadata_type=asset_service.AnalyzeIamPolicyLongrunningMetadata, + ) + + # Done; return the response. + return response + + async def analyze_move(self, + request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeMoveResponse: + r"""Analyze moving a resource to a specified destination + without kicking off the actual move. The analysis is + best effort depending on the user's permissions of + viewing different hierarchical policies and + configurations. The policies and configuration are + subject to change before the actual resource migration + takes place. + + .. 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 asset_v1 + + async def sample_analyze_move(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeMoveRequest( + resource="resource_value", + destination_parent="destination_parent_value", + ) + + # Make the request + response = await client.analyze_move(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.AnalyzeMoveRequest, dict]]): + The request object. The request message for performing + resource move analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.AnalyzeMoveResponse: + The response message for resource + move analysis. + + """ + # Create or coerce a protobuf request object. + request = asset_service.AnalyzeMoveRequest(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.analyze_move, + 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 query_assets(self, + request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.QueryAssetsResponse: + r"""Issue a job that queries assets using a SQL statement compatible + with `BigQuery + SQL `__. + + If the query execution finishes within timeout and there's no + pagination, the full query results will be returned in the + ``QueryAssetsResponse``. + + Otherwise, full query results can be obtained by issuing extra + requests with the ``job_reference`` from the a previous + ``QueryAssets`` call. + + Note, the query result has approximately 10 GB limitation + enforced by + `BigQuery `__. + Queries return larger results will result in errors. + + .. 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 asset_v1 + + async def sample_query_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.QueryAssetsRequest( + statement="statement_value", + parent="parent_value", + ) + + # Make the request + response = await client.query_assets(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.QueryAssetsRequest, dict]]): + The request object. QueryAssets request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.QueryAssetsResponse: + QueryAssets response. + """ + # Create or coerce a protobuf request object. + request = asset_service.QueryAssetsRequest(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.query_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=200.0, + ), + default_timeout=200.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 create_saved_query(self, + request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, + *, + parent: Optional[str] = None, + saved_query: Optional[asset_service.SavedQuery] = None, + saved_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.SavedQuery: + r"""Creates a saved query in a parent + project/folder/organization. + + .. 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 asset_v1 + + async def sample_create_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.CreateSavedQueryRequest( + parent="parent_value", + saved_query_id="saved_query_id_value", + ) + + # Make the request + response = await client.create_saved_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.CreateSavedQueryRequest, dict]]): + The request object. Request to create a saved query. + parent (:class:`str`): + Required. The name of the project/folder/organization + where this saved_query should be created in. It can only + be an organization number (such as "organizations/123"), + a folder number (such as "folders/123"), a project ID + (such as "projects/my-project-id"), or a project number + (such as "projects/12345"). + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + saved_query (:class:`google.cloud.asset_v1.types.SavedQuery`): + Required. The saved_query details. The ``name`` field + must be empty as it will be generated based on the + parent and saved_query_id. + + This corresponds to the ``saved_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + saved_query_id (:class:`str`): + Required. The ID to use for the saved query, which must + be unique in the specified parent. It will become the + final component of the saved query's resource name. + + This value should be 4-63 characters, and valid + characters are ``[a-z][0-9]-``. + + Notice that this field is required in the saved query + creation, and the ``name`` field of the ``saved_query`` + will be ignored. + + This corresponds to the ``saved_query_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.asset_v1.types.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + # 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, saved_query, saved_query_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 = asset_service.CreateSavedQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if saved_query is not None: + request.saved_query = saved_query + if saved_query_id is not None: + request.saved_query_id = saved_query_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_saved_query, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_saved_query(self, + request: Optional[Union[asset_service.GetSavedQueryRequest, 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]] = (), + ) -> asset_service.SavedQuery: + r"""Gets details about a saved query. + + .. 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 asset_v1 + + async def sample_get_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.GetSavedQueryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_saved_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.GetSavedQueryRequest, dict]]): + The request object. Request to get a saved query. + name (:class:`str`): + Required. The name of the saved query and it must be in + the format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + 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.asset_v1.types.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + # 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 = asset_service.GetSavedQueryRequest(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_saved_query, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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_saved_queries(self, + request: Optional[Union[asset_service.ListSavedQueriesRequest, 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.ListSavedQueriesAsyncPager: + r"""Lists all saved queries in a parent + project/folder/organization. + + .. 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 asset_v1 + + async def sample_list_saved_queries(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.ListSavedQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_saved_queries(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.ListSavedQueriesRequest, dict]]): + The request object. Request to list saved queries. + parent (:class:`str`): + Required. The parent + project/folder/organization whose + savedQueries are to be listed. It can + only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-id"). + + 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.asset_v1.services.asset_service.pagers.ListSavedQueriesAsyncPager: + Response of listing saved queries. + + 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 = asset_service.ListSavedQueriesRequest(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_saved_queries, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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.ListSavedQueriesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_saved_query(self, + request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, + *, + saved_query: Optional[asset_service.SavedQuery] = 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]] = (), + ) -> asset_service.SavedQuery: + r"""Updates a saved query. + + .. 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 asset_v1 + + async def sample_update_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.UpdateSavedQueryRequest( + ) + + # Make the request + response = await client.update_saved_query(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.UpdateSavedQueryRequest, dict]]): + The request object. Request to update a saved query. + saved_query (:class:`google.cloud.asset_v1.types.SavedQuery`): + Required. The saved query to update. + + The saved query's ``name`` field is used to identify the + one to update, which has format as below: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + This corresponds to the ``saved_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. The list of fields to + update. + + 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.asset_v1.types.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + # 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([saved_query, 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 = asset_service.UpdateSavedQueryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if saved_query is not None: + request.saved_query = saved_query + 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_saved_query, + 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(( + ("saved_query.name", request.saved_query.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_saved_query(self, + request: Optional[Union[asset_service.DeleteSavedQueryRequest, 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"""Deletes a saved query. + + .. 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 asset_v1 + + async def sample_delete_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.DeleteSavedQueryRequest( + name="name_value", + ) + + # Make the request + await client.delete_saved_query(request=request) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.DeleteSavedQueryRequest, dict]]): + The request object. Request to delete a saved query. + name (:class:`str`): + Required. The name of the saved query to delete. It must + be in the format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + 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 = asset_service.DeleteSavedQueryRequest(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_saved_query, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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 batch_get_effective_iam_policies(self, + request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + r"""Gets effective IAM policies for a batch of resources. + + .. 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 asset_v1 + + async def sample_batch_get_effective_iam_policies(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetEffectiveIamPoliciesRequest( + scope="scope_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = await client.batch_get_effective_iam_policies(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest, dict]]): + The request object. A request message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.BatchGetEffectiveIamPoliciesResponse: + A response message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + + """ + # Create or coerce a protobuf request object. + request = asset_service.BatchGetEffectiveIamPoliciesRequest(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.batch_get_effective_iam_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.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(( + ("scope", request.scope), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_org_policies(self, + request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AnalyzeOrgPoliciesAsyncPager: + r"""Analyzes organization policies under a scope. + + .. 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 asset_v1 + + async def sample_analyze_org_policies(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPoliciesRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest, dict]]): + The request object. A request message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + scope (:class:`str`): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + constraint (:class:`str`): + Required. The name of the constraint + to analyze organization policies for. + The response only contains analyzed + organization policies for the provided + constraint. + + This corresponds to the ``constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The expression to filter + [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. + The only supported field is + ``consolidated_policy.attached_resource``, and the only + supported operator is ``=``. + + Example: + consolidated_policy.attached_resource="//cloudresourcemanager.googleapis.com/folders/001" + will return the org policy results of"folders/001". + + This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesAsyncPager: + The response message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + + 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([scope, constraint, filter]) + 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 = asset_service.AnalyzeOrgPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if constraint is not None: + request.constraint = constraint + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.analyze_org_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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(( + ("scope", request.scope), + )), + ) + + # 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.AnalyzeOrgPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_org_policy_governed_containers(self, + request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager: + r"""Analyzes organization policies governed containers + (projects, folders or organization) under a scope. + + .. 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 asset_v1 + + async def sample_analyze_org_policy_governed_containers(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_containers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest, dict]]): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + scope (:class:`str`): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. + The output containers will also be limited to the ones + governed by those in-scope organization policies. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + constraint (:class:`str`): + Required. The name of the constraint + to analyze governed containers for. The + analysis only contains organization + policies for the provided constraint. + + This corresponds to the ``constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The expression to filter the governed containers in + result. The only supported field is ``parent``, and the + only supported operator is ``=``. + + Example: + parent="//cloudresourcemanager.googleapis.com/folders/001" + will return all containers under "folders/001". + + This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + + 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([scope, constraint, filter]) + 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 = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if constraint is not None: + request.constraint = constraint + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.analyze_org_policy_governed_containers, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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(( + ("scope", request.scope), + )), + ) + + # 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.AnalyzeOrgPolicyGovernedContainersAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def analyze_org_policy_governed_assets(self, + request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager: + r"""Analyzes organization policies governed assets (Google Cloud + resources or policies) under a scope. This RPC supports custom + constraints and the following 10 canned constraints: + + - storage.uniformBucketLevelAccess + - iam.disableServiceAccountKeyCreation + - iam.allowedPolicyMemberDomains + - compute.vmExternalIpAccess + - appengine.enforceServiceAccountActAsCheck + - gcp.resourceLocations + - compute.trustedImageProjects + - compute.skipDefaultNetworkCreation + - compute.requireOsLogin + - compute.disableNestedVirtualization + + This RPC only returns either resources of types supported by + `searchable asset + types `__, + or IAM policies. + + .. 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 asset_v1 + + async def sample_analyze_org_policy_governed_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest, dict]]): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + scope (:class:`str`): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. + The output assets will also be limited to the ones + governed by those in-scope organization policies. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + constraint (:class:`str`): + Required. The name of the constraint + to analyze governed assets for. The + analysis only contains analyzed + organization policies for the provided + constraint. + + This corresponds to the ``constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (:class:`str`): + The expression to filter the governed assets in result. + The only supported fields for governed resources are + ``governed_resource.project`` and + ``governed_resource.folders``. The only supported fields + for governed iam policies are + ``governed_iam_policy.project`` and + ``governed_iam_policy.folders``. The only supported + operator is ``=``. + + Example 1: governed_resource.project="projects/12345678" + filter will return all governed resources under + projects/12345678 including the project ifself, if + applicable. + + Example 2: + governed_iam_policy.folders="folders/12345678" filter + will return all governed iam policies under + folders/12345678, if applicable. + + This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + + 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([scope, constraint, filter]) + 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if constraint is not None: + request.constraint = constraint + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.analyze_org_policy_governed_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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(( + ("scope", request.scope), + )), + ) + + # 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.AnalyzeOrgPolicyGovernedAssetsAsyncPager( + method=rpc, + request=request, + response=response, + 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 __aenter__(self) -> "AssetServiceAsyncClient": + 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__ = ( + "AssetServiceAsyncClient", +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py new file mode 100644 index 00000000..7a9d4c08 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py @@ -0,0 +1,3329 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.asset_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.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .transports.rest import AssetServiceRestTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService 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[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AssetServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AssetServiceTransport]: + """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 AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @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 = "cloudasset.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: + AssetServiceClient: 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: + AssetServiceClient: 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) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def access_level_path(access_policy: str,access_level: str,) -> str: + """Returns a fully-qualified access_level string.""" + return "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) + + @staticmethod + def parse_access_level_path(path: str) -> Dict[str,str]: + """Parses a access_level path into its component segments.""" + m = re.match(r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def access_policy_path(access_policy: str,) -> str: + """Returns a fully-qualified access_policy string.""" + return "accessPolicies/{access_policy}".format(access_policy=access_policy, ) + + @staticmethod + def parse_access_policy_path(path: str) -> Dict[str,str]: + """Parses a access_policy path into its component segments.""" + m = re.match(r"^accessPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def asset_path() -> str: + """Returns a fully-qualified asset string.""" + return "*".format() + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^.*$", path) + return m.groupdict() if m else {} + + @staticmethod + def feed_path(project: str,feed: str,) -> str: + """Returns a fully-qualified feed string.""" + return "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) + + @staticmethod + def parse_feed_path(path: str) -> Dict[str,str]: + """Parses a feed path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def inventory_path(project: str,location: str,instance: str,) -> str: + """Returns a fully-qualified inventory string.""" + return "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) + + @staticmethod + def parse_inventory_path(path: str) -> Dict[str,str]: + """Parses a inventory path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", path) + return m.groupdict() if m else {} + + @staticmethod + def saved_query_path(project: str,saved_query: str,) -> str: + """Returns a fully-qualified saved_query string.""" + return "projects/{project}/savedQueries/{saved_query}".format(project=project, saved_query=saved_query, ) + + @staticmethod + def parse_saved_query_path(path: str) -> Dict[str,str]: + """Parses a saved_query path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_perimeter_path(access_policy: str,service_perimeter: str,) -> str: + """Returns a fully-qualified service_perimeter string.""" + return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) + + @staticmethod + def parse_service_perimeter_path(path: str) -> Dict[str,str]: + """Parses a service_perimeter path into its component segments.""" + m = re.match(r"^accessPolicies/(?P.+?)/servicePerimeters/(?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, AssetServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): + # transport is a AssetServiceTransport 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 export_assets(self, + request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset Protobuf as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] + API, which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + .. 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 asset_v1 + + def sample_export_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + output_config = asset_v1.OutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.ExportAssetsRequest( + parent="parent_value", + output_config=output_config, + ) + + # Make the request + operation = client.export_assets(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.ExportAssetsRequest, dict]): + The request object. Export asset request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.ExportAssetsResponse` The export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.ExportAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ExportAssetsRequest): + request = asset_service.ExportAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_assets] + + # 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, + asset_service.ExportAssetsResponse, + metadata_type=asset_service.ExportAssetsRequest, + ) + + # Done; return the response. + return response + + def list_assets(self, + request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + .. 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 asset_v1 + + def sample_list_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.ListAssetsRequest, dict]): + The request object. ListAssets request. + parent (str): + Required. Name of the organization, folder, or project + the assets belong to. Format: + "organizations/[organization-number]" (such as + "organizations/123"), "projects/[project-id]" (such as + "projects/my-project-id"), "projects/[project-number]" + (such as "projects/12345"), or "folders/[folder-number]" + (such as "folders/12345"). + + 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.asset_v1.services.asset_service.pagers.ListAssetsPager: + ListAssets response. + + 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 asset_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListAssetsRequest): + request = asset_service.ListAssetsRequest(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_assets] + + # 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.ListAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_get_assets_history(self, + request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetAssetsHistoryResponse: + r"""Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + .. 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 asset_v1 + + def sample_batch_get_assets_history(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetAssetsHistoryRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_get_assets_history(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest, dict]): + The request object. Batch get assets history request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.BatchGetAssetsHistoryResponse: + Batch get assets history response. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.BatchGetAssetsHistoryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.BatchGetAssetsHistoryRequest): + request = asset_service.BatchGetAssetsHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_get_assets_history] + + # 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 create_feed(self, + request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + .. 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 asset_v1 + + def sample_create_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = client.create_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.CreateFeedRequest, dict]): + The request object. Create asset feed request. + parent (str): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id"), or a + project number (such as + "projects/12345"). + + 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.asset_v1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + # 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 asset_service.CreateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.CreateFeedRequest): + request = asset_service.CreateFeedRequest(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.create_feed] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_feed(self, + request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + .. 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 asset_v1 + + def sample_get_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = client.get_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.GetFeedRequest, dict]): + The request object. Get asset feed request. + name (str): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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.asset_v1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + # 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 asset_service.GetFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.GetFeedRequest): + request = asset_service.GetFeedRequest(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_feed] + + # 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_feeds(self, + request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + .. 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 asset_v1 + + def sample_list_feeds(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_feeds(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.ListFeedsRequest, dict]): + The request object. List asset feeds request. + parent (str): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-id"). + + 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.asset_v1.types.ListFeedsResponse: + + """ + # 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 asset_service.ListFeedsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListFeedsRequest): + request = asset_service.ListFeedsRequest(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_feeds] + + # 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_feed(self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + .. 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 asset_v1 + + def sample_update_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = client.update_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.UpdateFeedRequest, dict]): + The request object. Update asset feed request. + feed (google.cloud.asset_v1.types.Feed): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + + This corresponds to the ``feed`` 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.asset_v1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + # 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([feed]) + 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 asset_service.UpdateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.UpdateFeedRequest): + request = asset_service.UpdateFeedRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if feed is not None: + request.feed = feed + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_feed] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("feed.name", request.feed.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_feed(self, + request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. + + .. 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 asset_v1 + + def sample_delete_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + client.delete_feed(request=request) + + Args: + request (Union[google.cloud.asset_v1.types.DeleteFeedRequest, dict]): + The request object. + name (str): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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 asset_service.DeleteFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.DeleteFeedRequest): + request = asset_service.DeleteFeedRequest(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_feed] + + # 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 search_all_resources(self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesPager: + r"""Searches all Google Cloud resources within the specified scope, + such as a project, folder, or organization. The caller must be + granted the ``cloudasset.assets.searchAllResources`` permission + on the desired scope, otherwise the request will be rejected. + + .. 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 asset_v1 + + def sample_search_all_resources(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.SearchAllResourcesRequest, dict]): + The request object. Search all resources request. + scope (str): + Required. A scope can be a project, a folder, or an + organization. The search is limited to the resources + within the ``scope``. The caller must be granted the + ```cloudasset.assets.searchAllResources`` `__ + permission on the desired scope. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + Optional. The query statement. See `how to construct a + query `__ + for more information. If not specified or empty, it will + search all the resources within the specified ``scope``. + + Examples: + + - ``name:Important`` to find Google Cloud resources + whose name contains ``Important`` as a word. + - ``name=Important`` to find the Google Cloud resource + whose name is exactly ``Important``. + - ``displayName:Impor*`` to find Google Cloud resources + whose display name contains ``Impor`` as a prefix of + any word in the field. + - ``location:us-west*`` to find Google Cloud resources + whose location contains both ``us`` and ``west`` as + prefixes. + - ``labels:prod`` to find Google Cloud resources whose + labels contain ``prod`` as a key or value. + - ``labels.env:prod`` to find Google Cloud resources + that have a label ``env`` and its value is ``prod``. + - ``labels.env:*`` to find Google Cloud resources that + have a label ``env``. + - ``tagKeys:env`` to find Google Cloud resources that + have directly attached tags where the + ```TagKey`` `__ + .\ ``namespacedName`` contains ``env``. + - ``tagValues:prod*`` to find Google Cloud resources + that have directly attached tags where the + ```TagValue`` `__ + .\ ``namespacedName`` contains a word prefixed by + ``prod``. + - ``tagValueIds=tagValues/123`` to find Google Cloud + resources that have directly attached tags where the + ```TagValue`` `__ + .\ ``name`` is exactly ``tagValues/123``. + - ``effectiveTagKeys:env`` to find Google Cloud + resources that have directly attached or inherited + tags where the + ```TagKey`` `__ + .\ ``namespacedName`` contains ``env``. + - ``effectiveTagValues:prod*`` to find Google Cloud + resources that have directly attached or inherited + tags where the + ```TagValue`` `__ + .\ ``namespacedName`` contains a word prefixed by + ``prod``. + - ``effectiveTagValueIds=tagValues/123`` to find Google + Cloud resources that have directly attached or + inherited tags where the + ```TagValue`` `__ + .\ ``name`` is exactly ``tagValues/123``. + - ``kmsKey:key`` to find Google Cloud resources + encrypted with a customer-managed encryption key + whose name contains ``key`` as a word. This field is + deprecated. Please use the ``kmsKeys`` field to + retrieve Cloud KMS key information. + - ``kmsKeys:key`` to find Google Cloud resources + encrypted with customer-managed encryption keys whose + name contains the word ``key``. + - ``relationships:instance-group-1`` to find Google + Cloud resources that have relationships with + ``instance-group-1`` in the related resource name. + - ``relationships:INSTANCE_TO_INSTANCEGROUP`` to find + Compute Engine instances that have relationships of + type ``INSTANCE_TO_INSTANCEGROUP``. + - ``relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1`` + to find Compute Engine instances that have + relationships with ``instance-group-1`` in the + Compute Engine instance group resource name, for + relationship type ``INSTANCE_TO_INSTANCEGROUP``. + - ``state:ACTIVE`` to find Google Cloud resources whose + state contains ``ACTIVE`` as a word. + - ``NOT state:ACTIVE`` to find Google Cloud resources + whose state doesn't contain ``ACTIVE`` as a word. + - ``createTime<1609459200`` to find Google Cloud + resources that were created before + ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the + epoch timestamp of ``2021-01-01 00:00:00 UTC`` in + seconds. + - ``updateTime>1609459200`` to find Google Cloud + resources that were updated after + ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the + epoch timestamp of ``2021-01-01 00:00:00 UTC`` in + seconds. + - ``Important`` to find Google Cloud resources that + contain ``Important`` as a word in any of the + searchable fields. + - ``Impor*`` to find Google Cloud resources that + contain ``Impor`` as a prefix of any word in any of + the searchable fields. + - ``Important location:(us-west1 OR global)`` to find + Google Cloud resources that contain ``Important`` as + a word in any of the searchable fields and are also + located in the ``us-west1`` region or the ``global`` + location. + + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (MutableSequence[str]): + Optional. A list of asset types that this request + searches for. If empty, it will search all the + `searchable asset + types `__. + + Regular expressions are also supported. For example: + + - "compute.googleapis.com.*" snapshots resources whose + asset type starts with "compute.googleapis.com". + - ".*Instance" snapshots resources whose asset type + ends with "Instance". + - ".*Instance.*" snapshots resources whose asset type + contains "Instance". + + See `RE2 `__ + for all supported regular expression syntax. If the + regular expression does not match any supported asset + type, an INVALID_ARGUMENT error will be returned. + + This corresponds to the ``asset_types`` 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.asset_v1.services.asset_service.pagers.SearchAllResourcesPager: + Search all resources response. + + 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([scope, query, asset_types]) + 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 asset_service.SearchAllResourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllResourcesRequest): + request = asset_service.SearchAllResourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types is not None: + request.asset_types = asset_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllResourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_all_iam_policies(self, + request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesPager: + r"""Searches all IAM policies within the specified scope, such as a + project, folder, or organization. The caller must be granted the + ``cloudasset.assets.searchAllIamPolicies`` permission on the + desired scope, otherwise the request will be rejected. + + .. 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 asset_v1 + + def sample_search_all_iam_policies(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.SearchAllIamPoliciesRequest, dict]): + The request object. Search all IAM policies request. + scope (str): + Required. A scope can be a project, a folder, or an + organization. The search is limited to the IAM policies + within the ``scope``. The caller must be granted the + ```cloudasset.assets.searchAllIamPolicies`` `__ + permission on the desired scope. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + Optional. The query statement. See `how to construct a + query `__ + for more information. If not specified or empty, it will + search all the IAM policies within the specified + ``scope``. Note that the query string is compared + against each IAM policy binding, including its + principals, roles, and IAM conditions. The returned IAM + policies will only contain the bindings that match your + query. To learn more about the IAM policy structure, see + the `IAM policy + documentation `__. + + Examples: + + - ``policy:amy@gmail.com`` to find IAM policy bindings + that specify user "amy@gmail.com". + - ``policy:roles/compute.admin`` to find IAM policy + bindings that specify the Compute Admin role. + - ``policy:comp*`` to find IAM policy bindings that + contain "comp" as a prefix of any word in the + binding. + - ``policy.role.permissions:storage.buckets.update`` to + find IAM policy bindings that specify a role + containing "storage.buckets.update" permission. Note + that if callers don't have ``iam.roles.get`` access + to a role's included permissions, policy bindings + that specify this role will be dropped from the + search results. + - ``policy.role.permissions:upd*`` to find IAM policy + bindings that specify a role containing "upd" as a + prefix of any word in the role permission. Note that + if callers don't have ``iam.roles.get`` access to a + role's included permissions, policy bindings that + specify this role will be dropped from the search + results. + - ``resource:organizations/123456`` to find IAM policy + bindings that are set on "organizations/123456". + - ``resource=//cloudresourcemanager.googleapis.com/projects/myproject`` + to find IAM policy bindings that are set on the + project named "myproject". + - ``Important`` to find IAM policy bindings that + contain "Important" as a word in any of the + searchable fields (except for the included + permissions). + - ``resource:(instance1 OR instance2) policy:amy`` to + find IAM policy bindings that are set on resources + "instance1" or "instance2" and also specify user + "amy". + - ``roles:roles/compute.admin`` to find IAM policy + bindings that specify the Compute Admin role. + - ``memberTypes:user`` to find IAM policy bindings that + contain the principal type "user". + + This corresponds to the ``query`` 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.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesPager: + Search all IAM policies response. + + 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([scope, query]) + 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 asset_service.SearchAllIamPoliciesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): + request = asset_service.SearchAllIamPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_iam_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllIamPoliciesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_iam_policy(self, + request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies to answer which identities have + what accesses on which resources. + + .. 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 asset_v1 + + def sample_analyze_iam_policy(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + request = asset_v1.AnalyzeIamPolicyRequest( + analysis_query=analysis_query, + ) + + # Make the request + response = client.analyze_iam_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.AnalyzeIamPolicyRequest, dict]): + The request object. A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.AnalyzeIamPolicyResponse: + A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.AnalyzeIamPolicyRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.AnalyzeIamPolicyRequest): + request = asset_service.AnalyzeIamPolicyRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis_query.scope", request.analysis_query.scope), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_iam_policy_longrunning(self, + request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Analyzes IAM policies asynchronously to answer which identities + have what accesses on which resources, and writes the analysis + results to a Google Cloud Storage or a BigQuery destination. For + Cloud Storage destination, the output format is the JSON format + that represents a + [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. + This method implements the + [google.longrunning.Operation][google.longrunning.Operation], + which allows you to track the operation status. We recommend + intervals of at least 2 seconds with exponential backoff retry + to poll the operation result. The metadata contains the metadata + for the long-running operation. + + .. 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 asset_v1 + + def sample_analyze_iam_policy_longrunning(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + output_config = asset_v1.IamPolicyAnalysisOutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.AnalyzeIamPolicyLongrunningRequest( + analysis_query=analysis_query, + output_config=output_config, + ) + + # Make the request + operation = client.analyze_iam_policy_longrunning(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest, dict]): + The request object. A request message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.AnalyzeIamPolicyLongrunningResponse` A response message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.AnalyzeIamPolicyLongrunningRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.AnalyzeIamPolicyLongrunningRequest): + request = asset_service.AnalyzeIamPolicyLongrunningRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy_longrunning] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis_query.scope", request.analysis_query.scope), + )), + ) + + # 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, + asset_service.AnalyzeIamPolicyLongrunningResponse, + metadata_type=asset_service.AnalyzeIamPolicyLongrunningMetadata, + ) + + # Done; return the response. + return response + + def analyze_move(self, + request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeMoveResponse: + r"""Analyze moving a resource to a specified destination + without kicking off the actual move. The analysis is + best effort depending on the user's permissions of + viewing different hierarchical policies and + configurations. The policies and configuration are + subject to change before the actual resource migration + takes place. + + .. 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 asset_v1 + + def sample_analyze_move(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeMoveRequest( + resource="resource_value", + destination_parent="destination_parent_value", + ) + + # Make the request + response = client.analyze_move(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.AnalyzeMoveRequest, dict]): + The request object. The request message for performing + resource move analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.AnalyzeMoveResponse: + The response message for resource + move analysis. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.AnalyzeMoveRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.AnalyzeMoveRequest): + request = asset_service.AnalyzeMoveRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_move] + + # 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 query_assets(self, + request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.QueryAssetsResponse: + r"""Issue a job that queries assets using a SQL statement compatible + with `BigQuery + SQL `__. + + If the query execution finishes within timeout and there's no + pagination, the full query results will be returned in the + ``QueryAssetsResponse``. + + Otherwise, full query results can be obtained by issuing extra + requests with the ``job_reference`` from the a previous + ``QueryAssets`` call. + + Note, the query result has approximately 10 GB limitation + enforced by + `BigQuery `__. + Queries return larger results will result in errors. + + .. 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 asset_v1 + + def sample_query_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.QueryAssetsRequest( + statement="statement_value", + parent="parent_value", + ) + + # Make the request + response = client.query_assets(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.QueryAssetsRequest, dict]): + The request object. QueryAssets request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.QueryAssetsResponse: + QueryAssets response. + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.QueryAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.QueryAssetsRequest): + request = asset_service.QueryAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_assets] + + # 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 create_saved_query(self, + request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, + *, + parent: Optional[str] = None, + saved_query: Optional[asset_service.SavedQuery] = None, + saved_query_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.SavedQuery: + r"""Creates a saved query in a parent + project/folder/organization. + + .. 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 asset_v1 + + def sample_create_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.CreateSavedQueryRequest( + parent="parent_value", + saved_query_id="saved_query_id_value", + ) + + # Make the request + response = client.create_saved_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.CreateSavedQueryRequest, dict]): + The request object. Request to create a saved query. + parent (str): + Required. The name of the project/folder/organization + where this saved_query should be created in. It can only + be an organization number (such as "organizations/123"), + a folder number (such as "folders/123"), a project ID + (such as "projects/my-project-id"), or a project number + (such as "projects/12345"). + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + saved_query (google.cloud.asset_v1.types.SavedQuery): + Required. The saved_query details. The ``name`` field + must be empty as it will be generated based on the + parent and saved_query_id. + + This corresponds to the ``saved_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + saved_query_id (str): + Required. The ID to use for the saved query, which must + be unique in the specified parent. It will become the + final component of the saved query's resource name. + + This value should be 4-63 characters, and valid + characters are ``[a-z][0-9]-``. + + Notice that this field is required in the saved query + creation, and the ``name`` field of the ``saved_query`` + will be ignored. + + This corresponds to the ``saved_query_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.asset_v1.types.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + # 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, saved_query, saved_query_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 asset_service.CreateSavedQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.CreateSavedQueryRequest): + request = asset_service.CreateSavedQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if saved_query is not None: + request.saved_query = saved_query + if saved_query_id is not None: + request.saved_query_id = saved_query_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_saved_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_saved_query(self, + request: Optional[Union[asset_service.GetSavedQueryRequest, 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]] = (), + ) -> asset_service.SavedQuery: + r"""Gets details about a saved query. + + .. 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 asset_v1 + + def sample_get_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.GetSavedQueryRequest( + name="name_value", + ) + + # Make the request + response = client.get_saved_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.GetSavedQueryRequest, dict]): + The request object. Request to get a saved query. + name (str): + Required. The name of the saved query and it must be in + the format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + 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.asset_v1.types.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + # 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 asset_service.GetSavedQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.GetSavedQueryRequest): + request = asset_service.GetSavedQueryRequest(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_saved_query] + + # 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_saved_queries(self, + request: Optional[Union[asset_service.ListSavedQueriesRequest, 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.ListSavedQueriesPager: + r"""Lists all saved queries in a parent + project/folder/organization. + + .. 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 asset_v1 + + def sample_list_saved_queries(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.ListSavedQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_saved_queries(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.ListSavedQueriesRequest, dict]): + The request object. Request to list saved queries. + parent (str): + Required. The parent + project/folder/organization whose + savedQueries are to be listed. It can + only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-id"). + + 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.asset_v1.services.asset_service.pagers.ListSavedQueriesPager: + Response of listing saved queries. + + 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 asset_service.ListSavedQueriesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListSavedQueriesRequest): + request = asset_service.ListSavedQueriesRequest(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_saved_queries] + + # 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.ListSavedQueriesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_saved_query(self, + request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, + *, + saved_query: Optional[asset_service.SavedQuery] = 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]] = (), + ) -> asset_service.SavedQuery: + r"""Updates a saved query. + + .. 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 asset_v1 + + def sample_update_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.UpdateSavedQueryRequest( + ) + + # Make the request + response = client.update_saved_query(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.UpdateSavedQueryRequest, dict]): + The request object. Request to update a saved query. + saved_query (google.cloud.asset_v1.types.SavedQuery): + Required. The saved query to update. + + The saved query's ``name`` field is used to identify the + one to update, which has format as below: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + This corresponds to the ``saved_query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to + update. + + 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.asset_v1.types.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + # 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([saved_query, 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 asset_service.UpdateSavedQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.UpdateSavedQueryRequest): + request = asset_service.UpdateSavedQueryRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if saved_query is not None: + request.saved_query = saved_query + 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_saved_query] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("saved_query.name", request.saved_query.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_saved_query(self, + request: Optional[Union[asset_service.DeleteSavedQueryRequest, 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"""Deletes a saved query. + + .. 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 asset_v1 + + def sample_delete_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.DeleteSavedQueryRequest( + name="name_value", + ) + + # Make the request + client.delete_saved_query(request=request) + + Args: + request (Union[google.cloud.asset_v1.types.DeleteSavedQueryRequest, dict]): + The request object. Request to delete a saved query. + name (str): + Required. The name of the saved query to delete. It must + be in the format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + 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 asset_service.DeleteSavedQueryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.DeleteSavedQueryRequest): + request = asset_service.DeleteSavedQueryRequest(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_saved_query] + + # 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 batch_get_effective_iam_policies(self, + request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + r"""Gets effective IAM policies for a batch of resources. + + .. 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 asset_v1 + + def sample_batch_get_effective_iam_policies(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetEffectiveIamPoliciesRequest( + scope="scope_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_get_effective_iam_policies(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest, dict]): + The request object. A request message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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.asset_v1.types.BatchGetEffectiveIamPoliciesResponse: + A response message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + + """ + # Create or coerce a protobuf request object. + # Minor optimization to avoid making a copy if the user passes + # in a asset_service.BatchGetEffectiveIamPoliciesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.BatchGetEffectiveIamPoliciesRequest): + request = asset_service.BatchGetEffectiveIamPoliciesRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_get_effective_iam_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_org_policies(self, + request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AnalyzeOrgPoliciesPager: + r"""Analyzes organization policies under a scope. + + .. 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 asset_v1 + + def sample_analyze_org_policies(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPoliciesRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest, dict]): + The request object. A request message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + scope (str): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + constraint (str): + Required. The name of the constraint + to analyze organization policies for. + The response only contains analyzed + organization policies for the provided + constraint. + + This corresponds to the ``constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The expression to filter + [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. + The only supported field is + ``consolidated_policy.attached_resource``, and the only + supported operator is ``=``. + + Example: + consolidated_policy.attached_resource="//cloudresourcemanager.googleapis.com/folders/001" + will return the org policy results of"folders/001". + + This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesPager: + The response message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + + 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([scope, constraint, filter]) + 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 asset_service.AnalyzeOrgPoliciesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.AnalyzeOrgPoliciesRequest): + request = asset_service.AnalyzeOrgPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if constraint is not None: + request.constraint = constraint + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_org_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # 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.AnalyzeOrgPoliciesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_org_policy_governed_containers(self, + request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: + r"""Analyzes organization policies governed containers + (projects, folders or organization) under a scope. + + .. 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 asset_v1 + + def sample_analyze_org_policy_governed_containers(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_containers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest, dict]): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + scope (str): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. + The output containers will also be limited to the ones + governed by those in-scope organization policies. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + constraint (str): + Required. The name of the constraint + to analyze governed containers for. The + analysis only contains organization + policies for the provided constraint. + + This corresponds to the ``constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The expression to filter the governed containers in + result. The only supported field is ``parent``, and the + only supported operator is ``=``. + + Example: + parent="//cloudresourcemanager.googleapis.com/folders/001" + will return all containers under "folders/001". + + This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersPager: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + + 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([scope, constraint, filter]) + 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 asset_service.AnalyzeOrgPolicyGovernedContainersRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if constraint is not None: + request.constraint = constraint + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_containers] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # 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.AnalyzeOrgPolicyGovernedContainersPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def analyze_org_policy_governed_assets(self, + request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, + *, + scope: Optional[str] = None, + constraint: Optional[str] = None, + filter: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: + r"""Analyzes organization policies governed assets (Google Cloud + resources or policies) under a scope. This RPC supports custom + constraints and the following 10 canned constraints: + + - storage.uniformBucketLevelAccess + - iam.disableServiceAccountKeyCreation + - iam.allowedPolicyMemberDomains + - compute.vmExternalIpAccess + - appengine.enforceServiceAccountActAsCheck + - gcp.resourceLocations + - compute.trustedImageProjects + - compute.skipDefaultNetworkCreation + - compute.requireOsLogin + - compute.disableNestedVirtualization + + This RPC only returns either resources of types supported by + `searchable asset + types `__, + or IAM policies. + + .. 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 asset_v1 + + def sample_analyze_org_policy_governed_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest, dict]): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + scope (str): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. + The output assets will also be limited to the ones + governed by those in-scope organization policies. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + constraint (str): + Required. The name of the constraint + to analyze governed assets for. The + analysis only contains analyzed + organization policies for the provided + constraint. + + This corresponds to the ``constraint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + filter (str): + The expression to filter the governed assets in result. + The only supported fields for governed resources are + ``governed_resource.project`` and + ``governed_resource.folders``. The only supported fields + for governed iam policies are + ``governed_iam_policy.project`` and + ``governed_iam_policy.folders``. The only supported + operator is ``=``. + + Example 1: governed_resource.project="projects/12345678" + filter will return all governed resources under + projects/12345678 including the project ifself, if + applicable. + + Example 2: + governed_iam_policy.folders="folders/12345678" filter + will return all governed iam policies under + folders/12345678, if applicable. + + This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsPager: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + + 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([scope, constraint, filter]) + 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 asset_service.AnalyzeOrgPolicyGovernedAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): + request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if constraint is not None: + request.constraint = constraint + if filter is not None: + request.filter = filter + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_assets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # 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.AnalyzeOrgPolicyGovernedAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AssetServiceClient": + 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 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 + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AssetServiceClient", +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py new file mode 100644 index 00000000..8f71ac0d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py @@ -0,0 +1,866 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.ListAssetsResponse` + 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[..., asset_service.ListAssetsResponse], + request: asset_service.ListAssetsRequest, + response: asset_service.ListAssetsResponse, + *, + 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.asset_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.asset_v1.types.ListAssetsResponse): + 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 = asset_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.ListAssetsResponse]: + 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[assets.Asset]: + for page in self.pages: + yield from page.assets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.ListAssetsResponse` + 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[asset_service.ListAssetsResponse]], + request: asset_service.ListAssetsRequest, + response: asset_service.ListAssetsResponse, + *, + 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.asset_v1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.asset_v1.types.ListAssetsResponse): + 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 = asset_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.ListAssetsResponse]: + 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[assets.Asset]: + async def async_generator(): + async for page in self.pages: + for response in page.assets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAllResourcesPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` + 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[..., asset_service.SearchAllResourcesResponse], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + 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.asset_v1.types.SearchAllResourcesRequest): + The initial request object. + response (google.cloud.asset_v1.types.SearchAllResourcesResponse): + 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 = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.SearchAllResourcesResponse]: + 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[assets.ResourceSearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAllResourcesAsyncPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` + 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[asset_service.SearchAllResourcesResponse]], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + 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.asset_v1.types.SearchAllResourcesRequest): + The initial request object. + response (google.cloud.asset_v1.types.SearchAllResourcesResponse): + 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 = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.SearchAllResourcesResponse]: + 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[assets.ResourceSearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` + 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[..., asset_service.SearchAllIamPoliciesResponse], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + 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.asset_v1.types.SearchAllIamPoliciesRequest): + The initial request object. + response (google.cloud.asset_v1.types.SearchAllIamPoliciesResponse): + 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 = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.SearchAllIamPoliciesResponse]: + 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[assets.IamPolicySearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesAsyncPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` + 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[asset_service.SearchAllIamPoliciesResponse]], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + 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.asset_v1.types.SearchAllIamPoliciesRequest): + The initial request object. + response (google.cloud.asset_v1.types.SearchAllIamPoliciesResponse): + 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 = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.SearchAllIamPoliciesResponse]: + 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[assets.IamPolicySearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSavedQueriesPager: + """A pager for iterating through ``list_saved_queries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``saved_queries`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSavedQueries`` requests and continue to iterate + through the ``saved_queries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` + 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[..., asset_service.ListSavedQueriesResponse], + request: asset_service.ListSavedQueriesRequest, + response: asset_service.ListSavedQueriesResponse, + *, + 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.asset_v1.types.ListSavedQueriesRequest): + The initial request object. + response (google.cloud.asset_v1.types.ListSavedQueriesResponse): + 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 = asset_service.ListSavedQueriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.ListSavedQueriesResponse]: + 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[asset_service.SavedQuery]: + for page in self.pages: + yield from page.saved_queries + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListSavedQueriesAsyncPager: + """A pager for iterating through ``list_saved_queries`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``saved_queries`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSavedQueries`` requests and continue to iterate + through the ``saved_queries`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` + 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[asset_service.ListSavedQueriesResponse]], + request: asset_service.ListSavedQueriesRequest, + response: asset_service.ListSavedQueriesResponse, + *, + 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.asset_v1.types.ListSavedQueriesRequest): + The initial request object. + response (google.cloud.asset_v1.types.ListSavedQueriesResponse): + 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 = asset_service.ListSavedQueriesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.ListSavedQueriesResponse]: + 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[asset_service.SavedQuery]: + async def async_generator(): + async for page in self.pages: + for response in page.saved_queries: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class AnalyzeOrgPoliciesPager: + """A pager for iterating through ``analyze_org_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``org_policy_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``AnalyzeOrgPolicies`` requests and continue to iterate + through the ``org_policy_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` + 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[..., asset_service.AnalyzeOrgPoliciesResponse], + request: asset_service.AnalyzeOrgPoliciesRequest, + response: asset_service.AnalyzeOrgPoliciesResponse, + *, + 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.asset_v1.types.AnalyzeOrgPoliciesRequest): + The initial request object. + response (google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse): + 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 = asset_service.AnalyzeOrgPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.AnalyzeOrgPoliciesResponse]: + 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[asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult]: + for page in self.pages: + yield from page.org_policy_results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class AnalyzeOrgPoliciesAsyncPager: + """A pager for iterating through ``analyze_org_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``org_policy_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``AnalyzeOrgPolicies`` requests and continue to iterate + through the ``org_policy_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` + 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[asset_service.AnalyzeOrgPoliciesResponse]], + request: asset_service.AnalyzeOrgPoliciesRequest, + response: asset_service.AnalyzeOrgPoliciesResponse, + *, + 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.asset_v1.types.AnalyzeOrgPoliciesRequest): + The initial request object. + response (google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse): + 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 = asset_service.AnalyzeOrgPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.AnalyzeOrgPoliciesResponse]: + 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[asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult]: + async def async_generator(): + async for page in self.pages: + for response in page.org_policy_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class AnalyzeOrgPolicyGovernedContainersPager: + """A pager for iterating through ``analyze_org_policy_governed_containers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``governed_containers`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``AnalyzeOrgPolicyGovernedContainers`` requests and continue to iterate + through the ``governed_containers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` + 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[..., asset_service.AnalyzeOrgPolicyGovernedContainersResponse], + request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, + response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + *, + 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.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest): + The initial request object. + response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse): + 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 = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: + 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[asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer]: + for page in self.pages: + yield from page.governed_containers + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class AnalyzeOrgPolicyGovernedContainersAsyncPager: + """A pager for iterating through ``analyze_org_policy_governed_containers`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``governed_containers`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``AnalyzeOrgPolicyGovernedContainers`` requests and continue to iterate + through the ``governed_containers`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` + 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[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]], + request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, + response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + *, + 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.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest): + The initial request object. + response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse): + 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 = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: + 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[asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer]: + async def async_generator(): + async for page in self.pages: + for response in page.governed_containers: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class AnalyzeOrgPolicyGovernedAssetsPager: + """A pager for iterating through ``analyze_org_policy_governed_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``governed_assets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``AnalyzeOrgPolicyGovernedAssets`` requests and continue to iterate + through the ``governed_assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` + 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[..., asset_service.AnalyzeOrgPolicyGovernedAssetsResponse], + request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, + response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + *, + 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.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest): + The initial request object. + response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse): + 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: + 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[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset]: + for page in self.pages: + yield from page.governed_assets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class AnalyzeOrgPolicyGovernedAssetsAsyncPager: + """A pager for iterating through ``analyze_org_policy_governed_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``governed_assets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``AnalyzeOrgPolicyGovernedAssets`` requests and continue to iterate + through the ``governed_assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` + 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[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]], + request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, + response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + *, + 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.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest): + The initial request object. + response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse): + 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: + 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[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset]: + async def async_generator(): + async for page in self.pages: + for response in page.governed_assets: + 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/asset_v1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..c34a5f8f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .rest import AssetServiceRestTransport +from .rest import AssetServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AssetServiceRestTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', + 'AssetServiceRestTransport', + 'AssetServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py new file mode 100644 index 00000000..c2b0fe0d --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -0,0 +1,580 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.asset_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.asset_v1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudasset.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.export_assets: gapic_v1.method.wrap_method( + self.export_assets, + default_timeout=60.0, + client_info=client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.batch_get_assets_history: gapic_v1.method.wrap_method( + self.batch_get_assets_history, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_feed: gapic_v1.method.wrap_method( + self.create_feed, + default_timeout=60.0, + client_info=client_info, + ), + self.get_feed: gapic_v1.method.wrap_method( + self.get_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_feeds: gapic_v1.method.wrap_method( + self.list_feeds, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_feed: gapic_v1.method.wrap_method( + self.update_feed, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_feed: gapic_v1.method.wrap_method( + self.delete_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.search_all_resources: gapic_v1.method.wrap_method( + self.search_all_resources, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.search_all_iam_policies: gapic_v1.method.wrap_method( + self.search_all_iam_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=30.0, + ), + default_timeout=30.0, + client_info=client_info, + ), + self.analyze_iam_policy: gapic_v1.method.wrap_method( + self.analyze_iam_policy, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.analyze_iam_policy_longrunning: gapic_v1.method.wrap_method( + self.analyze_iam_policy_longrunning, + default_timeout=60.0, + client_info=client_info, + ), + self.analyze_move: gapic_v1.method.wrap_method( + self.analyze_move, + default_timeout=None, + client_info=client_info, + ), + self.query_assets: gapic_v1.method.wrap_method( + self.query_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=200.0, + ), + default_timeout=200.0, + client_info=client_info, + ), + self.create_saved_query: gapic_v1.method.wrap_method( + self.create_saved_query, + default_timeout=60.0, + client_info=client_info, + ), + self.get_saved_query: gapic_v1.method.wrap_method( + self.get_saved_query, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_saved_queries: gapic_v1.method.wrap_method( + self.list_saved_queries, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_saved_query: gapic_v1.method.wrap_method( + self.update_saved_query, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_saved_query: gapic_v1.method.wrap_method( + self.delete_saved_query, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.batch_get_effective_iam_policies: gapic_v1.method.wrap_method( + self.batch_get_effective_iam_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=300.0, + ), + default_timeout=300.0, + client_info=client_info, + ), + self.analyze_org_policies: gapic_v1.method.wrap_method( + self.analyze_org_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.analyze_org_policy_governed_containers: gapic_v1.method.wrap_method( + self.analyze_org_policy_governed_containers, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.analyze_org_policy_governed_assets: gapic_v1.method.wrap_method( + self.analyze_org_policy_governed_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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 operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def export_assets(self) -> Callable[ + [asset_service.ExportAssetsRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + Union[ + asset_service.ListAssetsResponse, + Awaitable[asset_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def batch_get_assets_history(self) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + Union[ + asset_service.BatchGetAssetsHistoryResponse, + Awaitable[asset_service.BatchGetAssetsHistoryResponse] + ]]: + raise NotImplementedError() + + @property + def create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: + raise NotImplementedError() + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: + raise NotImplementedError() + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + Union[ + asset_service.ListFeedsResponse, + Awaitable[asset_service.ListFeedsResponse] + ]]: + raise NotImplementedError() + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: + raise NotImplementedError() + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Union[ + asset_service.SearchAllResourcesResponse, + Awaitable[asset_service.SearchAllResourcesResponse] + ]]: + raise NotImplementedError() + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Union[ + asset_service.SearchAllIamPoliciesResponse, + Awaitable[asset_service.SearchAllIamPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def analyze_iam_policy(self) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + Union[ + asset_service.AnalyzeIamPolicyResponse, + Awaitable[asset_service.AnalyzeIamPolicyResponse] + ]]: + raise NotImplementedError() + + @property + def analyze_iam_policy_longrunning(self) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def analyze_move(self) -> Callable[ + [asset_service.AnalyzeMoveRequest], + Union[ + asset_service.AnalyzeMoveResponse, + Awaitable[asset_service.AnalyzeMoveResponse] + ]]: + raise NotImplementedError() + + @property + def query_assets(self) -> Callable[ + [asset_service.QueryAssetsRequest], + Union[ + asset_service.QueryAssetsResponse, + Awaitable[asset_service.QueryAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def create_saved_query(self) -> Callable[ + [asset_service.CreateSavedQueryRequest], + Union[ + asset_service.SavedQuery, + Awaitable[asset_service.SavedQuery] + ]]: + raise NotImplementedError() + + @property + def get_saved_query(self) -> Callable[ + [asset_service.GetSavedQueryRequest], + Union[ + asset_service.SavedQuery, + Awaitable[asset_service.SavedQuery] + ]]: + raise NotImplementedError() + + @property + def list_saved_queries(self) -> Callable[ + [asset_service.ListSavedQueriesRequest], + Union[ + asset_service.ListSavedQueriesResponse, + Awaitable[asset_service.ListSavedQueriesResponse] + ]]: + raise NotImplementedError() + + @property + def update_saved_query(self) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + Union[ + asset_service.SavedQuery, + Awaitable[asset_service.SavedQuery] + ]]: + raise NotImplementedError() + + @property + def delete_saved_query(self) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def batch_get_effective_iam_policies(self) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + Union[ + asset_service.BatchGetEffectiveIamPoliciesResponse, + Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def analyze_org_policies(self) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + Union[ + asset_service.AnalyzeOrgPoliciesResponse, + Awaitable[asset_service.AnalyzeOrgPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def analyze_org_policy_governed_containers(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse] + ]]: + raise NotImplementedError() + + @property + def analyze_org_policy_governed_assets(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + Union[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, + Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AssetServiceTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..2dfa44ec --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -0,0 +1,959 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.asset_v1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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 export_assets(self) -> Callable[ + [asset_service.ExportAssetsRequest], + operations_pb2.Operation]: + r"""Return a callable for the export assets method over gRPC. + + Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset Protobuf as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] + API, which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + Returns: + Callable[[~.ExportAssetsRequest], + ~.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 'export_assets' not in self._stubs: + self._stubs['export_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ExportAssets', + request_serializer=asset_service.ExportAssetsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_assets'] + + @property + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + asset_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists assets with time and resource types and returns + paged results in response. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + 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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListAssets', + request_serializer=asset_service.ListAssetsRequest.serialize, + response_deserializer=asset_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def batch_get_assets_history(self) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + asset_service.BatchGetAssetsHistoryResponse]: + r"""Return a callable for the batch get assets history method over gRPC. + + Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + Returns: + Callable[[~.BatchGetAssetsHistoryRequest], + ~.BatchGetAssetsHistoryResponse]: + 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 'batch_get_assets_history' not in self._stubs: + self._stubs['batch_get_assets_history'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory', + request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, + response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, + ) + return self._stubs['batch_get_assets_history'] + + @property + def create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + asset_service.Feed]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + ~.Feed]: + 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_feed' not in self._stubs: + self._stubs['create_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/CreateFeed', + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['create_feed'] + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + asset_service.Feed]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + ~.Feed]: + 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_feed' not in self._stubs: + self._stubs['get_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/GetFeed', + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['get_feed'] + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + asset_service.ListFeedsResponse]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + ~.ListFeedsResponse]: + 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_feeds' not in self._stubs: + self._stubs['list_feeds'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListFeeds', + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs['list_feeds'] + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + asset_service.Feed]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + ~.Feed]: + 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_feed' not in self._stubs: + self._stubs['update_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/UpdateFeed', + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['update_feed'] + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + ~.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_feed' not in self._stubs: + self._stubs['delete_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/DeleteFeed', + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_feed'] + + @property + def search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all Google Cloud resources within the specified scope, + such as a project, folder, or organization. The caller must be + granted the ``cloudasset.assets.searchAllResources`` permission + on the desired scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + ~.SearchAllResourcesResponse]: + 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 'search_all_resources' not in self._stubs: + self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/SearchAllResources', + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs['search_all_resources'] + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all IAM policies within the specified scope, such as a + project, folder, or organization. The caller must be granted the + ``cloudasset.assets.searchAllIamPolicies`` permission on the + desired scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + ~.SearchAllIamPoliciesResponse]: + 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 'search_all_iam_policies' not in self._stubs: + self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/SearchAllIamPolicies', + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs['search_all_iam_policies'] + + @property + def analyze_iam_policy(self) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + asset_service.AnalyzeIamPolicyResponse]: + r"""Return a callable for the analyze iam policy method over gRPC. + + Analyzes IAM policies to answer which identities have + what accesses on which resources. + + Returns: + Callable[[~.AnalyzeIamPolicyRequest], + ~.AnalyzeIamPolicyResponse]: + 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 'analyze_iam_policy' not in self._stubs: + self._stubs['analyze_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy', + request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, + response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, + ) + return self._stubs['analyze_iam_policy'] + + @property + def analyze_iam_policy_longrunning(self) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + operations_pb2.Operation]: + r"""Return a callable for the analyze iam policy longrunning method over gRPC. + + Analyzes IAM policies asynchronously to answer which identities + have what accesses on which resources, and writes the analysis + results to a Google Cloud Storage or a BigQuery destination. For + Cloud Storage destination, the output format is the JSON format + that represents a + [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. + This method implements the + [google.longrunning.Operation][google.longrunning.Operation], + which allows you to track the operation status. We recommend + intervals of at least 2 seconds with exponential backoff retry + to poll the operation result. The metadata contains the metadata + for the long-running operation. + + Returns: + Callable[[~.AnalyzeIamPolicyLongrunningRequest], + ~.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 'analyze_iam_policy_longrunning' not in self._stubs: + self._stubs['analyze_iam_policy_longrunning'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning', + request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['analyze_iam_policy_longrunning'] + + @property + def analyze_move(self) -> Callable[ + [asset_service.AnalyzeMoveRequest], + asset_service.AnalyzeMoveResponse]: + r"""Return a callable for the analyze move method over gRPC. + + Analyze moving a resource to a specified destination + without kicking off the actual move. The analysis is + best effort depending on the user's permissions of + viewing different hierarchical policies and + configurations. The policies and configuration are + subject to change before the actual resource migration + takes place. + + Returns: + Callable[[~.AnalyzeMoveRequest], + ~.AnalyzeMoveResponse]: + 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 'analyze_move' not in self._stubs: + self._stubs['analyze_move'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeMove', + request_serializer=asset_service.AnalyzeMoveRequest.serialize, + response_deserializer=asset_service.AnalyzeMoveResponse.deserialize, + ) + return self._stubs['analyze_move'] + + @property + def query_assets(self) -> Callable[ + [asset_service.QueryAssetsRequest], + asset_service.QueryAssetsResponse]: + r"""Return a callable for the query assets method over gRPC. + + Issue a job that queries assets using a SQL statement compatible + with `BigQuery + SQL `__. + + If the query execution finishes within timeout and there's no + pagination, the full query results will be returned in the + ``QueryAssetsResponse``. + + Otherwise, full query results can be obtained by issuing extra + requests with the ``job_reference`` from the a previous + ``QueryAssets`` call. + + Note, the query result has approximately 10 GB limitation + enforced by + `BigQuery `__. + Queries return larger results will result in errors. + + Returns: + Callable[[~.QueryAssetsRequest], + ~.QueryAssetsResponse]: + 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 'query_assets' not in self._stubs: + self._stubs['query_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/QueryAssets', + request_serializer=asset_service.QueryAssetsRequest.serialize, + response_deserializer=asset_service.QueryAssetsResponse.deserialize, + ) + return self._stubs['query_assets'] + + @property + def create_saved_query(self) -> Callable[ + [asset_service.CreateSavedQueryRequest], + asset_service.SavedQuery]: + r"""Return a callable for the create saved query method over gRPC. + + Creates a saved query in a parent + project/folder/organization. + + Returns: + Callable[[~.CreateSavedQueryRequest], + ~.SavedQuery]: + 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_saved_query' not in self._stubs: + self._stubs['create_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/CreateSavedQuery', + request_serializer=asset_service.CreateSavedQueryRequest.serialize, + response_deserializer=asset_service.SavedQuery.deserialize, + ) + return self._stubs['create_saved_query'] + + @property + def get_saved_query(self) -> Callable[ + [asset_service.GetSavedQueryRequest], + asset_service.SavedQuery]: + r"""Return a callable for the get saved query method over gRPC. + + Gets details about a saved query. + + Returns: + Callable[[~.GetSavedQueryRequest], + ~.SavedQuery]: + 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_saved_query' not in self._stubs: + self._stubs['get_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/GetSavedQuery', + request_serializer=asset_service.GetSavedQueryRequest.serialize, + response_deserializer=asset_service.SavedQuery.deserialize, + ) + return self._stubs['get_saved_query'] + + @property + def list_saved_queries(self) -> Callable[ + [asset_service.ListSavedQueriesRequest], + asset_service.ListSavedQueriesResponse]: + r"""Return a callable for the list saved queries method over gRPC. + + Lists all saved queries in a parent + project/folder/organization. + + Returns: + Callable[[~.ListSavedQueriesRequest], + ~.ListSavedQueriesResponse]: + 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_saved_queries' not in self._stubs: + self._stubs['list_saved_queries'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListSavedQueries', + request_serializer=asset_service.ListSavedQueriesRequest.serialize, + response_deserializer=asset_service.ListSavedQueriesResponse.deserialize, + ) + return self._stubs['list_saved_queries'] + + @property + def update_saved_query(self) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + asset_service.SavedQuery]: + r"""Return a callable for the update saved query method over gRPC. + + Updates a saved query. + + Returns: + Callable[[~.UpdateSavedQueryRequest], + ~.SavedQuery]: + 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_saved_query' not in self._stubs: + self._stubs['update_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/UpdateSavedQuery', + request_serializer=asset_service.UpdateSavedQueryRequest.serialize, + response_deserializer=asset_service.SavedQuery.deserialize, + ) + return self._stubs['update_saved_query'] + + @property + def delete_saved_query(self) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete saved query method over gRPC. + + Deletes a saved query. + + Returns: + Callable[[~.DeleteSavedQueryRequest], + ~.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_saved_query' not in self._stubs: + self._stubs['delete_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/DeleteSavedQuery', + request_serializer=asset_service.DeleteSavedQueryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_saved_query'] + + @property + def batch_get_effective_iam_policies(self) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + asset_service.BatchGetEffectiveIamPoliciesResponse]: + r"""Return a callable for the batch get effective iam + policies method over gRPC. + + Gets effective IAM policies for a batch of resources. + + Returns: + Callable[[~.BatchGetEffectiveIamPoliciesRequest], + ~.BatchGetEffectiveIamPoliciesResponse]: + 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 'batch_get_effective_iam_policies' not in self._stubs: + self._stubs['batch_get_effective_iam_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies', + request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, + response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, + ) + return self._stubs['batch_get_effective_iam_policies'] + + @property + def analyze_org_policies(self) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + asset_service.AnalyzeOrgPoliciesResponse]: + r"""Return a callable for the analyze org policies method over gRPC. + + Analyzes organization policies under a scope. + + Returns: + Callable[[~.AnalyzeOrgPoliciesRequest], + ~.AnalyzeOrgPoliciesResponse]: + 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 'analyze_org_policies' not in self._stubs: + self._stubs['analyze_org_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies', + request_serializer=asset_service.AnalyzeOrgPoliciesRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPoliciesResponse.deserialize, + ) + return self._stubs['analyze_org_policies'] + + @property + def analyze_org_policy_governed_containers(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: + r"""Return a callable for the analyze org policy governed + containers method over gRPC. + + Analyzes organization policies governed containers + (projects, folders or organization) under a scope. + + Returns: + Callable[[~.AnalyzeOrgPolicyGovernedContainersRequest], + ~.AnalyzeOrgPolicyGovernedContainersResponse]: + 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 'analyze_org_policy_governed_containers' not in self._stubs: + self._stubs['analyze_org_policy_governed_containers'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers', + request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, + ) + return self._stubs['analyze_org_policy_governed_containers'] + + @property + def analyze_org_policy_governed_assets(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: + r"""Return a callable for the analyze org policy governed + assets method over gRPC. + + Analyzes organization policies governed assets (Google Cloud + resources or policies) under a scope. This RPC supports custom + constraints and the following 10 canned constraints: + + - storage.uniformBucketLevelAccess + - iam.disableServiceAccountKeyCreation + - iam.allowedPolicyMemberDomains + - compute.vmExternalIpAccess + - appengine.enforceServiceAccountActAsCheck + - gcp.resourceLocations + - compute.trustedImageProjects + - compute.skipDefaultNetworkCreation + - compute.requireOsLogin + - compute.disableNestedVirtualization + + This RPC only returns either resources of types supported by + `searchable asset + types `__, + or IAM policies. + + Returns: + Callable[[~.AnalyzeOrgPolicyGovernedAssetsRequest], + ~.AnalyzeOrgPolicyGovernedAssetsResponse]: + 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 'analyze_org_policy_governed_assets' not in self._stubs: + self._stubs['analyze_org_policy_governed_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets', + request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, + ) + return self._stubs['analyze_org_policy_governed_assets'] + + def close(self): + self.grpc_channel.close() + + @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 kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AssetServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..373e65ad --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,958 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.asset_v1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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 export_assets(self) -> Callable[ + [asset_service.ExportAssetsRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export assets method over gRPC. + + Exports assets with time and resource types to a given Cloud + Storage location/BigQuery table. For Cloud Storage location + destinations, the output format is newline-delimited JSON. Each + line represents a + [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in + the JSON format; for BigQuery table destinations, the output + table stores the fields in asset Protobuf as columns. This API + implements the + [google.longrunning.Operation][google.longrunning.Operation] + API, which allows you to keep track of the export. We recommend + intervals of at least 2 seconds with exponential retry to poll + the export operation result. For regular-size resource parent, + the export operation usually finishes within 5 minutes. + + Returns: + Callable[[~.ExportAssetsRequest], + 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 'export_assets' not in self._stubs: + self._stubs['export_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ExportAssets', + request_serializer=asset_service.ExportAssetsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_assets'] + + @property + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + Awaitable[asset_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists assets with time and resource types and returns + paged results in response. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + 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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListAssets', + request_serializer=asset_service.ListAssetsRequest.serialize, + response_deserializer=asset_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + @property + def batch_get_assets_history(self) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + Awaitable[asset_service.BatchGetAssetsHistoryResponse]]: + r"""Return a callable for the batch get assets history method over gRPC. + + Batch gets the update history of assets that overlap a time + window. For IAM_POLICY content, this API outputs history when + the asset and its attached IAM POLICY both exist. This can + create gaps in the output history. Otherwise, this API outputs + history with asset in both non-delete or deleted status. If a + specified asset does not exist, this API returns an + INVALID_ARGUMENT error. + + Returns: + Callable[[~.BatchGetAssetsHistoryRequest], + Awaitable[~.BatchGetAssetsHistoryResponse]]: + 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 'batch_get_assets_history' not in self._stubs: + self._stubs['batch_get_assets_history'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory', + request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, + response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, + ) + return self._stubs['batch_get_assets_history'] + + @property + def create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + Awaitable[asset_service.Feed]]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + Awaitable[~.Feed]]: + 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_feed' not in self._stubs: + self._stubs['create_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/CreateFeed', + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['create_feed'] + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + Awaitable[asset_service.Feed]]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + Awaitable[~.Feed]]: + 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_feed' not in self._stubs: + self._stubs['get_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/GetFeed', + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['get_feed'] + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + Awaitable[asset_service.ListFeedsResponse]]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + Awaitable[~.ListFeedsResponse]]: + 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_feeds' not in self._stubs: + self._stubs['list_feeds'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListFeeds', + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs['list_feeds'] + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + Awaitable[asset_service.Feed]]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + Awaitable[~.Feed]]: + 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_feed' not in self._stubs: + self._stubs['update_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/UpdateFeed', + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['update_feed'] + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + 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_feed' not in self._stubs: + self._stubs['delete_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/DeleteFeed', + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_feed'] + + @property + def search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Awaitable[asset_service.SearchAllResourcesResponse]]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all Google Cloud resources within the specified scope, + such as a project, folder, or organization. The caller must be + granted the ``cloudasset.assets.searchAllResources`` permission + on the desired scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + Awaitable[~.SearchAllResourcesResponse]]: + 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 'search_all_resources' not in self._stubs: + self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/SearchAllResources', + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs['search_all_resources'] + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Awaitable[asset_service.SearchAllIamPoliciesResponse]]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all IAM policies within the specified scope, such as a + project, folder, or organization. The caller must be granted the + ``cloudasset.assets.searchAllIamPolicies`` permission on the + desired scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + Awaitable[~.SearchAllIamPoliciesResponse]]: + 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 'search_all_iam_policies' not in self._stubs: + self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/SearchAllIamPolicies', + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs['search_all_iam_policies'] + + @property + def analyze_iam_policy(self) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + Awaitable[asset_service.AnalyzeIamPolicyResponse]]: + r"""Return a callable for the analyze iam policy method over gRPC. + + Analyzes IAM policies to answer which identities have + what accesses on which resources. + + Returns: + Callable[[~.AnalyzeIamPolicyRequest], + Awaitable[~.AnalyzeIamPolicyResponse]]: + 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 'analyze_iam_policy' not in self._stubs: + self._stubs['analyze_iam_policy'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy', + request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, + response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, + ) + return self._stubs['analyze_iam_policy'] + + @property + def analyze_iam_policy_longrunning(self) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the analyze iam policy longrunning method over gRPC. + + Analyzes IAM policies asynchronously to answer which identities + have what accesses on which resources, and writes the analysis + results to a Google Cloud Storage or a BigQuery destination. For + Cloud Storage destination, the output format is the JSON format + that represents a + [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. + This method implements the + [google.longrunning.Operation][google.longrunning.Operation], + which allows you to track the operation status. We recommend + intervals of at least 2 seconds with exponential backoff retry + to poll the operation result. The metadata contains the metadata + for the long-running operation. + + Returns: + Callable[[~.AnalyzeIamPolicyLongrunningRequest], + 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 'analyze_iam_policy_longrunning' not in self._stubs: + self._stubs['analyze_iam_policy_longrunning'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning', + request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['analyze_iam_policy_longrunning'] + + @property + def analyze_move(self) -> Callable[ + [asset_service.AnalyzeMoveRequest], + Awaitable[asset_service.AnalyzeMoveResponse]]: + r"""Return a callable for the analyze move method over gRPC. + + Analyze moving a resource to a specified destination + without kicking off the actual move. The analysis is + best effort depending on the user's permissions of + viewing different hierarchical policies and + configurations. The policies and configuration are + subject to change before the actual resource migration + takes place. + + Returns: + Callable[[~.AnalyzeMoveRequest], + Awaitable[~.AnalyzeMoveResponse]]: + 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 'analyze_move' not in self._stubs: + self._stubs['analyze_move'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeMove', + request_serializer=asset_service.AnalyzeMoveRequest.serialize, + response_deserializer=asset_service.AnalyzeMoveResponse.deserialize, + ) + return self._stubs['analyze_move'] + + @property + def query_assets(self) -> Callable[ + [asset_service.QueryAssetsRequest], + Awaitable[asset_service.QueryAssetsResponse]]: + r"""Return a callable for the query assets method over gRPC. + + Issue a job that queries assets using a SQL statement compatible + with `BigQuery + SQL `__. + + If the query execution finishes within timeout and there's no + pagination, the full query results will be returned in the + ``QueryAssetsResponse``. + + Otherwise, full query results can be obtained by issuing extra + requests with the ``job_reference`` from the a previous + ``QueryAssets`` call. + + Note, the query result has approximately 10 GB limitation + enforced by + `BigQuery `__. + Queries return larger results will result in errors. + + Returns: + Callable[[~.QueryAssetsRequest], + Awaitable[~.QueryAssetsResponse]]: + 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 'query_assets' not in self._stubs: + self._stubs['query_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/QueryAssets', + request_serializer=asset_service.QueryAssetsRequest.serialize, + response_deserializer=asset_service.QueryAssetsResponse.deserialize, + ) + return self._stubs['query_assets'] + + @property + def create_saved_query(self) -> Callable[ + [asset_service.CreateSavedQueryRequest], + Awaitable[asset_service.SavedQuery]]: + r"""Return a callable for the create saved query method over gRPC. + + Creates a saved query in a parent + project/folder/organization. + + Returns: + Callable[[~.CreateSavedQueryRequest], + Awaitable[~.SavedQuery]]: + 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_saved_query' not in self._stubs: + self._stubs['create_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/CreateSavedQuery', + request_serializer=asset_service.CreateSavedQueryRequest.serialize, + response_deserializer=asset_service.SavedQuery.deserialize, + ) + return self._stubs['create_saved_query'] + + @property + def get_saved_query(self) -> Callable[ + [asset_service.GetSavedQueryRequest], + Awaitable[asset_service.SavedQuery]]: + r"""Return a callable for the get saved query method over gRPC. + + Gets details about a saved query. + + Returns: + Callable[[~.GetSavedQueryRequest], + Awaitable[~.SavedQuery]]: + 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_saved_query' not in self._stubs: + self._stubs['get_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/GetSavedQuery', + request_serializer=asset_service.GetSavedQueryRequest.serialize, + response_deserializer=asset_service.SavedQuery.deserialize, + ) + return self._stubs['get_saved_query'] + + @property + def list_saved_queries(self) -> Callable[ + [asset_service.ListSavedQueriesRequest], + Awaitable[asset_service.ListSavedQueriesResponse]]: + r"""Return a callable for the list saved queries method over gRPC. + + Lists all saved queries in a parent + project/folder/organization. + + Returns: + Callable[[~.ListSavedQueriesRequest], + Awaitable[~.ListSavedQueriesResponse]]: + 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_saved_queries' not in self._stubs: + self._stubs['list_saved_queries'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/ListSavedQueries', + request_serializer=asset_service.ListSavedQueriesRequest.serialize, + response_deserializer=asset_service.ListSavedQueriesResponse.deserialize, + ) + return self._stubs['list_saved_queries'] + + @property + def update_saved_query(self) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + Awaitable[asset_service.SavedQuery]]: + r"""Return a callable for the update saved query method over gRPC. + + Updates a saved query. + + Returns: + Callable[[~.UpdateSavedQueryRequest], + Awaitable[~.SavedQuery]]: + 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_saved_query' not in self._stubs: + self._stubs['update_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/UpdateSavedQuery', + request_serializer=asset_service.UpdateSavedQueryRequest.serialize, + response_deserializer=asset_service.SavedQuery.deserialize, + ) + return self._stubs['update_saved_query'] + + @property + def delete_saved_query(self) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete saved query method over gRPC. + + Deletes a saved query. + + Returns: + Callable[[~.DeleteSavedQueryRequest], + 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_saved_query' not in self._stubs: + self._stubs['delete_saved_query'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/DeleteSavedQuery', + request_serializer=asset_service.DeleteSavedQueryRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_saved_query'] + + @property + def batch_get_effective_iam_policies(self) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse]]: + r"""Return a callable for the batch get effective iam + policies method over gRPC. + + Gets effective IAM policies for a batch of resources. + + Returns: + Callable[[~.BatchGetEffectiveIamPoliciesRequest], + Awaitable[~.BatchGetEffectiveIamPoliciesResponse]]: + 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 'batch_get_effective_iam_policies' not in self._stubs: + self._stubs['batch_get_effective_iam_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies', + request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, + response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, + ) + return self._stubs['batch_get_effective_iam_policies'] + + @property + def analyze_org_policies(self) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + Awaitable[asset_service.AnalyzeOrgPoliciesResponse]]: + r"""Return a callable for the analyze org policies method over gRPC. + + Analyzes organization policies under a scope. + + Returns: + Callable[[~.AnalyzeOrgPoliciesRequest], + Awaitable[~.AnalyzeOrgPoliciesResponse]]: + 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 'analyze_org_policies' not in self._stubs: + self._stubs['analyze_org_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies', + request_serializer=asset_service.AnalyzeOrgPoliciesRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPoliciesResponse.deserialize, + ) + return self._stubs['analyze_org_policies'] + + @property + def analyze_org_policy_governed_containers(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]]: + r"""Return a callable for the analyze org policy governed + containers method over gRPC. + + Analyzes organization policies governed containers + (projects, folders or organization) under a scope. + + Returns: + Callable[[~.AnalyzeOrgPolicyGovernedContainersRequest], + Awaitable[~.AnalyzeOrgPolicyGovernedContainersResponse]]: + 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 'analyze_org_policy_governed_containers' not in self._stubs: + self._stubs['analyze_org_policy_governed_containers'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers', + request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, + ) + return self._stubs['analyze_org_policy_governed_containers'] + + @property + def analyze_org_policy_governed_assets(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]]: + r"""Return a callable for the analyze org policy governed + assets method over gRPC. + + Analyzes organization policies governed assets (Google Cloud + resources or policies) under a scope. This RPC supports custom + constraints and the following 10 canned constraints: + + - storage.uniformBucketLevelAccess + - iam.disableServiceAccountKeyCreation + - iam.allowedPolicyMemberDomains + - compute.vmExternalIpAccess + - appengine.enforceServiceAccountActAsCheck + - gcp.resourceLocations + - compute.trustedImageProjects + - compute.skipDefaultNetworkCreation + - compute.requireOsLogin + - compute.disableNestedVirtualization + + This RPC only returns either resources of types supported by + `searchable asset + types `__, + or IAM policies. + + Returns: + Callable[[~.AnalyzeOrgPolicyGovernedAssetsRequest], + Awaitable[~.AnalyzeOrgPolicyGovernedAssetsResponse]]: + 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 'analyze_org_policy_governed_assets' not in self._stubs: + self._stubs['analyze_org_policy_governed_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets', + request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, + response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, + ) + return self._stubs['analyze_org_policy_governed_assets'] + + def close(self): + return self.grpc_channel.close() + + @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"] + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py new file mode 100644 index 00000000..a5b80a83 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py @@ -0,0 +1,2899 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +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 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.asset_v1.types import asset_service +from google.protobuf import empty_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: + """Interceptor for AssetService. + + 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 AssetServiceRestTransport. + + .. code-block:: python + class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): + def pre_analyze_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_iam_policy_longrunning(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_iam_policy_longrunning(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_move(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_move(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_org_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_org_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_org_policy_governed_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_org_policy_governed_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_analyze_org_policy_governed_containers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_analyze_org_policy_governed_containers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_get_assets_history(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_get_assets_history(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_get_effective_iam_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_get_effective_iam_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_feed(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_saved_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_saved_query(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_saved_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_export_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_feed(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_saved_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_saved_query(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_feeds(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_feeds(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_saved_queries(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_saved_queries(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_query_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_query_assets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_all_iam_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_all_iam_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_all_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_all_resources(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_feed(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_saved_query(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_saved_query(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) + client = AssetServiceClient(transport=transport) + + + """ + def pre_analyze_iam_policy(self, request: asset_service.AnalyzeIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_analyze_iam_policy(self, response: asset_service.AnalyzeIamPolicyResponse) -> asset_service.AnalyzeIamPolicyResponse: + """Post-rpc interceptor for analyze_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_analyze_iam_policy_longrunning(self, request: asset_service.AnalyzeIamPolicyLongrunningRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeIamPolicyLongrunningRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_iam_policy_longrunning + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_analyze_iam_policy_longrunning(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for analyze_iam_policy_longrunning + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_analyze_move(self, request: asset_service.AnalyzeMoveRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeMoveRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_move + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_analyze_move(self, response: asset_service.AnalyzeMoveResponse) -> asset_service.AnalyzeMoveResponse: + """Post-rpc interceptor for analyze_move + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_analyze_org_policies(self, request: asset_service.AnalyzeOrgPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeOrgPoliciesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_org_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_analyze_org_policies(self, response: asset_service.AnalyzeOrgPoliciesResponse) -> asset_service.AnalyzeOrgPoliciesResponse: + """Post-rpc interceptor for analyze_org_policies + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_analyze_org_policy_governed_assets(self, request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_org_policy_governed_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_analyze_org_policy_governed_assets(self, response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: + """Post-rpc interceptor for analyze_org_policy_governed_assets + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_analyze_org_policy_governed_containers(self, request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for analyze_org_policy_governed_containers + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_analyze_org_policy_governed_containers(self, response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: + """Post-rpc interceptor for analyze_org_policy_governed_containers + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_batch_get_assets_history(self, request: asset_service.BatchGetAssetsHistoryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.BatchGetAssetsHistoryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_get_assets_history + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_batch_get_assets_history(self, response: asset_service.BatchGetAssetsHistoryResponse) -> asset_service.BatchGetAssetsHistoryResponse: + """Post-rpc interceptor for batch_get_assets_history + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_batch_get_effective_iam_policies(self, request: asset_service.BatchGetEffectiveIamPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.BatchGetEffectiveIamPoliciesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for batch_get_effective_iam_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_batch_get_effective_iam_policies(self, response: asset_service.BatchGetEffectiveIamPoliciesResponse) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + """Post-rpc interceptor for batch_get_effective_iam_policies + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_create_feed(self, request: asset_service.CreateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.CreateFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_create_feed(self, response: asset_service.Feed) -> asset_service.Feed: + """Post-rpc interceptor for create_feed + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_create_saved_query(self, request: asset_service.CreateSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.CreateSavedQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_saved_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_create_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: + """Post-rpc interceptor for create_saved_query + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_delete_feed(self, request: asset_service.DeleteFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.DeleteFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def pre_delete_saved_query(self, request: asset_service.DeleteSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.DeleteSavedQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_saved_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def pre_export_assets(self, request: asset_service.ExportAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ExportAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for export_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_export_assets(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for export_assets + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_get_feed(self, request: asset_service.GetFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.GetFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_get_feed(self, response: asset_service.Feed) -> asset_service.Feed: + """Post-rpc interceptor for get_feed + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_get_saved_query(self, request: asset_service.GetSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.GetSavedQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_saved_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_get_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: + """Post-rpc interceptor for get_saved_query + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_list_assets(self, request: asset_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_list_assets(self, response: asset_service.ListAssetsResponse) -> asset_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_list_feeds(self, request: asset_service.ListFeedsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListFeedsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_feeds + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_list_feeds(self, response: asset_service.ListFeedsResponse) -> asset_service.ListFeedsResponse: + """Post-rpc interceptor for list_feeds + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_list_saved_queries(self, request: asset_service.ListSavedQueriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListSavedQueriesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_saved_queries + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_list_saved_queries(self, response: asset_service.ListSavedQueriesResponse) -> asset_service.ListSavedQueriesResponse: + """Post-rpc interceptor for list_saved_queries + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_query_assets(self, request: asset_service.QueryAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.QueryAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for query_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_query_assets(self, response: asset_service.QueryAssetsResponse) -> asset_service.QueryAssetsResponse: + """Post-rpc interceptor for query_assets + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_search_all_iam_policies(self, request: asset_service.SearchAllIamPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllIamPoliciesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_all_iam_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_search_all_iam_policies(self, response: asset_service.SearchAllIamPoliciesResponse) -> asset_service.SearchAllIamPoliciesResponse: + """Post-rpc interceptor for search_all_iam_policies + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_search_all_resources(self, request: asset_service.SearchAllResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllResourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_all_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_search_all_resources(self, response: asset_service.SearchAllResourcesResponse) -> asset_service.SearchAllResourcesResponse: + """Post-rpc interceptor for search_all_resources + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_update_feed(self, request: asset_service.UpdateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.UpdateFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_update_feed(self, response: asset_service.Feed) -> asset_service.Feed: + """Post-rpc interceptor for update_feed + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_update_saved_query(self, request: asset_service.UpdateSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.UpdateSavedQueryRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_saved_query + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_update_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: + """Post-rpc interceptor for update_saved_query + + Override in a subclass to manipulate the response + after it is returned by the AssetService 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 AssetService 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 AssetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AssetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AssetServiceRestInterceptor + + +class AssetServiceRestTransport(AssetServiceTransport): + """REST backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() + 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.GetOperation': [ + { + 'method': 'get', + 'uri': '/v1/{name=*/*/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 _AnalyzeIamPolicy(AssetServiceRestStub): + def __hash__(self): + return hash("AnalyzeIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "analysisQuery" : {}, } + + @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: asset_service.AnalyzeIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Call the analyze iam policy method over HTTP. + + Args: + request (~.asset_service.AnalyzeIamPolicyRequest): + The request object. A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.AnalyzeIamPolicyResponse: + A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{analysis_query.scope=*/*}:analyzeIamPolicy', + }, + ] + request, metadata = self._interceptor.pre_analyze_iam_policy(request, metadata) + pb_request = asset_service.AnalyzeIamPolicyRequest.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 = asset_service.AnalyzeIamPolicyResponse() + pb_resp = asset_service.AnalyzeIamPolicyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_iam_policy(resp) + return resp + + class _AnalyzeIamPolicyLongrunning(AssetServiceRestStub): + def __hash__(self): + return hash("AnalyzeIamPolicyLongrunning") + + __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: asset_service.AnalyzeIamPolicyLongrunningRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the analyze iam policy + longrunning method over HTTP. + + Args: + request (~.asset_service.AnalyzeIamPolicyLongrunningRequest): + The request object. A request message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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/{analysis_query.scope=*/*}:analyzeIamPolicyLongrunning', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_analyze_iam_policy_longrunning(request, metadata) + pb_request = asset_service.AnalyzeIamPolicyLongrunningRequest.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_analyze_iam_policy_longrunning(resp) + return resp + + class _AnalyzeMove(AssetServiceRestStub): + def __hash__(self): + return hash("AnalyzeMove") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "destinationParent" : "", } + + @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: asset_service.AnalyzeMoveRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.AnalyzeMoveResponse: + r"""Call the analyze move method over HTTP. + + Args: + request (~.asset_service.AnalyzeMoveRequest): + The request object. The request message for performing + resource move analysis. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.AnalyzeMoveResponse: + The response message for resource + move analysis. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=*/*}:analyzeMove', + }, + ] + request, metadata = self._interceptor.pre_analyze_move(request, metadata) + pb_request = asset_service.AnalyzeMoveRequest.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 = asset_service.AnalyzeMoveResponse() + pb_resp = asset_service.AnalyzeMoveResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_move(resp) + return resp + + class _AnalyzeOrgPolicies(AssetServiceRestStub): + def __hash__(self): + return hash("AnalyzeOrgPolicies") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "constraint" : "", } + + @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: asset_service.AnalyzeOrgPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.AnalyzeOrgPoliciesResponse: + r"""Call the analyze org policies method over HTTP. + + Args: + request (~.asset_service.AnalyzeOrgPoliciesRequest): + The request object. A request message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.AnalyzeOrgPoliciesResponse: + The response message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{scope=*/*}:analyzeOrgPolicies', + }, + ] + request, metadata = self._interceptor.pre_analyze_org_policies(request, metadata) + pb_request = asset_service.AnalyzeOrgPoliciesRequest.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 = asset_service.AnalyzeOrgPoliciesResponse() + pb_resp = asset_service.AnalyzeOrgPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_org_policies(resp) + return resp + + class _AnalyzeOrgPolicyGovernedAssets(AssetServiceRestStub): + def __hash__(self): + return hash("AnalyzeOrgPolicyGovernedAssets") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "constraint" : "", } + + @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: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: + r"""Call the analyze org policy + governed assets method over HTTP. + + Args: + request (~.asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{scope=*/*}:analyzeOrgPolicyGovernedAssets', + }, + ] + request, metadata = self._interceptor.pre_analyze_org_policy_governed_assets(request, metadata) + pb_request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() + pb_resp = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_org_policy_governed_assets(resp) + return resp + + class _AnalyzeOrgPolicyGovernedContainers(AssetServiceRestStub): + def __hash__(self): + return hash("AnalyzeOrgPolicyGovernedContainers") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "constraint" : "", } + + @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: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: + r"""Call the analyze org policy + governed containers method over HTTP. + + Args: + request (~.asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + The request object. A request message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.AnalyzeOrgPolicyGovernedContainersResponse: + The response message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{scope=*/*}:analyzeOrgPolicyGovernedContainers', + }, + ] + request, metadata = self._interceptor.pre_analyze_org_policy_governed_containers(request, metadata) + pb_request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest.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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() + pb_resp = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_analyze_org_policy_governed_containers(resp) + return resp + + class _BatchGetAssetsHistory(AssetServiceRestStub): + def __hash__(self): + return hash("BatchGetAssetsHistory") + + __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: asset_service.BatchGetAssetsHistoryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.BatchGetAssetsHistoryResponse: + r"""Call the batch get assets history method over HTTP. + + Args: + request (~.asset_service.BatchGetAssetsHistoryRequest): + The request object. Batch get assets history request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.BatchGetAssetsHistoryResponse: + Batch get assets history response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=*/*}:batchGetAssetsHistory', + }, + ] + request, metadata = self._interceptor.pre_batch_get_assets_history(request, metadata) + pb_request = asset_service.BatchGetAssetsHistoryRequest.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 = asset_service.BatchGetAssetsHistoryResponse() + pb_resp = asset_service.BatchGetAssetsHistoryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_get_assets_history(resp) + return resp + + class _BatchGetEffectiveIamPolicies(AssetServiceRestStub): + def __hash__(self): + return hash("BatchGetEffectiveIamPolicies") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "names" : "", } + + @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: asset_service.BatchGetEffectiveIamPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: + r"""Call the batch get effective iam + policies method over HTTP. + + Args: + request (~.asset_service.BatchGetEffectiveIamPoliciesRequest): + The request object. A request message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.BatchGetEffectiveIamPoliciesResponse: + A response message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{scope=*/*}/effectiveIamPolicies:batchGet', + }, + ] + request, metadata = self._interceptor.pre_batch_get_effective_iam_policies(request, metadata) + pb_request = asset_service.BatchGetEffectiveIamPoliciesRequest.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 = asset_service.BatchGetEffectiveIamPoliciesResponse() + pb_resp = asset_service.BatchGetEffectiveIamPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_batch_get_effective_iam_policies(resp) + return resp + + class _CreateFeed(AssetServiceRestStub): + def __hash__(self): + return hash("CreateFeed") + + __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: asset_service.CreateFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.Feed: + r"""Call the create feed method over HTTP. + + Args: + request (~.asset_service.CreateFeedRequest): + The request object. Create asset feed request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=*/*}/feeds', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_create_feed(request, metadata) + pb_request = asset_service.CreateFeedRequest.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 = asset_service.Feed() + pb_resp = asset_service.Feed.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_feed(resp) + return resp + + class _CreateSavedQuery(AssetServiceRestStub): + def __hash__(self): + return hash("CreateSavedQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "savedQueryId" : "", } + + @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: asset_service.CreateSavedQueryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.SavedQuery: + r"""Call the create saved query method over HTTP. + + Args: + request (~.asset_service.CreateSavedQueryRequest): + The request object. Request to create a saved query. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=*/*}/savedQueries', + 'body': 'saved_query', + }, + ] + request, metadata = self._interceptor.pre_create_saved_query(request, metadata) + pb_request = asset_service.CreateSavedQueryRequest.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 = asset_service.SavedQuery() + pb_resp = asset_service.SavedQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_saved_query(resp) + return resp + + class _DeleteFeed(AssetServiceRestStub): + def __hash__(self): + return hash("DeleteFeed") + + __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: asset_service.DeleteFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete feed method over HTTP. + + Args: + request (~.asset_service.DeleteFeedRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1/{name=*/*/feeds/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_feed(request, metadata) + pb_request = asset_service.DeleteFeedRequest.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 _DeleteSavedQuery(AssetServiceRestStub): + def __hash__(self): + return hash("DeleteSavedQuery") + + __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: asset_service.DeleteSavedQueryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete saved query method over HTTP. + + Args: + request (~.asset_service.DeleteSavedQueryRequest): + The request object. Request to delete a saved query. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be 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=*/*/savedQueries/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_saved_query(request, metadata) + pb_request = asset_service.DeleteSavedQueryRequest.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 _ExportAssets(AssetServiceRestStub): + def __hash__(self): + return hash("ExportAssets") + + __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: asset_service.ExportAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the export assets method over HTTP. + + Args: + request (~.asset_service.ExportAssetsRequest): + The request object. Export asset request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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=*/*}:exportAssets', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_export_assets(request, metadata) + pb_request = asset_service.ExportAssetsRequest.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_export_assets(resp) + return resp + + class _GetFeed(AssetServiceRestStub): + def __hash__(self): + return hash("GetFeed") + + __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: asset_service.GetFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.Feed: + r"""Call the get feed method over HTTP. + + Args: + request (~.asset_service.GetFeedRequest): + The request object. Get asset feed request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=*/*/feeds/*}', + }, + ] + request, metadata = self._interceptor.pre_get_feed(request, metadata) + pb_request = asset_service.GetFeedRequest.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 = asset_service.Feed() + pb_resp = asset_service.Feed.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_feed(resp) + return resp + + class _GetSavedQuery(AssetServiceRestStub): + def __hash__(self): + return hash("GetSavedQuery") + + __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: asset_service.GetSavedQueryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.SavedQuery: + r"""Call the get saved query method over HTTP. + + Args: + request (~.asset_service.GetSavedQueryRequest): + The request object. Request to get a saved query. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=*/*/savedQueries/*}', + }, + ] + request, metadata = self._interceptor.pre_get_saved_query(request, metadata) + pb_request = asset_service.GetSavedQueryRequest.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 = asset_service.SavedQuery() + pb_resp = asset_service.SavedQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_saved_query(resp) + return resp + + class _ListAssets(AssetServiceRestStub): + def __hash__(self): + return hash("ListAssets") + + __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: asset_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.asset_service.ListAssetsRequest): + The request object. ListAssets request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListAssetsResponse: + ListAssets response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=*/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = asset_service.ListAssetsRequest.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 = asset_service.ListAssetsResponse() + pb_resp = asset_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + class _ListFeeds(AssetServiceRestStub): + def __hash__(self): + return hash("ListFeeds") + + __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: asset_service.ListFeedsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.ListFeedsResponse: + r"""Call the list feeds method over HTTP. + + Args: + request (~.asset_service.ListFeedsRequest): + The request object. List asset feeds request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListFeedsResponse: + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=*/*}/feeds', + }, + ] + request, metadata = self._interceptor.pre_list_feeds(request, metadata) + pb_request = asset_service.ListFeedsRequest.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 = asset_service.ListFeedsResponse() + pb_resp = asset_service.ListFeedsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_feeds(resp) + return resp + + class _ListSavedQueries(AssetServiceRestStub): + def __hash__(self): + return hash("ListSavedQueries") + + __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: asset_service.ListSavedQueriesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.ListSavedQueriesResponse: + r"""Call the list saved queries method over HTTP. + + Args: + request (~.asset_service.ListSavedQueriesRequest): + The request object. Request to list saved queries. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListSavedQueriesResponse: + Response of listing saved queries. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=*/*}/savedQueries', + }, + ] + request, metadata = self._interceptor.pre_list_saved_queries(request, metadata) + pb_request = asset_service.ListSavedQueriesRequest.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 = asset_service.ListSavedQueriesResponse() + pb_resp = asset_service.ListSavedQueriesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_saved_queries(resp) + return resp + + class _QueryAssets(AssetServiceRestStub): + def __hash__(self): + return hash("QueryAssets") + + __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: asset_service.QueryAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.QueryAssetsResponse: + r"""Call the query assets method over HTTP. + + Args: + request (~.asset_service.QueryAssetsRequest): + The request object. QueryAssets request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.QueryAssetsResponse: + QueryAssets response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=*/*}:queryAssets', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_query_assets(request, metadata) + pb_request = asset_service.QueryAssetsRequest.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 = asset_service.QueryAssetsResponse() + pb_resp = asset_service.QueryAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_query_assets(resp) + return resp + + class _SearchAllIamPolicies(AssetServiceRestStub): + def __hash__(self): + return hash("SearchAllIamPolicies") + + __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: asset_service.SearchAllIamPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.SearchAllIamPoliciesResponse: + r"""Call the search all iam policies method over HTTP. + + Args: + request (~.asset_service.SearchAllIamPoliciesRequest): + The request object. Search all IAM policies request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.SearchAllIamPoliciesResponse: + Search all IAM policies response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{scope=*/*}:searchAllIamPolicies', + }, + ] + request, metadata = self._interceptor.pre_search_all_iam_policies(request, metadata) + pb_request = asset_service.SearchAllIamPoliciesRequest.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 = asset_service.SearchAllIamPoliciesResponse() + pb_resp = asset_service.SearchAllIamPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_all_iam_policies(resp) + return resp + + class _SearchAllResources(AssetServiceRestStub): + def __hash__(self): + return hash("SearchAllResources") + + __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: asset_service.SearchAllResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.SearchAllResourcesResponse: + r"""Call the search all resources method over HTTP. + + Args: + request (~.asset_service.SearchAllResourcesRequest): + The request object. Search all resources request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.SearchAllResourcesResponse: + Search all resources response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{scope=*/*}:searchAllResources', + }, + ] + request, metadata = self._interceptor.pre_search_all_resources(request, metadata) + pb_request = asset_service.SearchAllResourcesRequest.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 = asset_service.SearchAllResourcesResponse() + pb_resp = asset_service.SearchAllResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_all_resources(resp) + return resp + + class _UpdateFeed(AssetServiceRestStub): + def __hash__(self): + return hash("UpdateFeed") + + __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: asset_service.UpdateFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.Feed: + r"""Call the update feed method over HTTP. + + Args: + request (~.asset_service.UpdateFeedRequest): + The request object. Update asset feed request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{feed.name=*/*/feeds/*}', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_update_feed(request, metadata) + pb_request = asset_service.UpdateFeedRequest.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 = asset_service.Feed() + pb_resp = asset_service.Feed.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_feed(resp) + return resp + + class _UpdateSavedQuery(AssetServiceRestStub): + def __hash__(self): + return hash("UpdateSavedQuery") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @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: asset_service.UpdateSavedQueryRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.SavedQuery: + r"""Call the update saved query method over HTTP. + + Args: + request (~.asset_service.UpdateSavedQueryRequest): + The request object. Request to update a saved query. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.SavedQuery: + A saved query which can be shared + with others or used later. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{saved_query.name=*/*/savedQueries/*}', + 'body': 'saved_query', + }, + ] + request, metadata = self._interceptor.pre_update_saved_query(request, metadata) + pb_request = asset_service.UpdateSavedQueryRequest.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 = asset_service.SavedQuery() + pb_resp = asset_service.SavedQuery.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_saved_query(resp) + return resp + + @property + def analyze_iam_policy(self) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + asset_service.AnalyzeIamPolicyResponse]: + # 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._AnalyzeIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_iam_policy_longrunning(self) -> Callable[ + [asset_service.AnalyzeIamPolicyLongrunningRequest], + 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._AnalyzeIamPolicyLongrunning(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_move(self) -> Callable[ + [asset_service.AnalyzeMoveRequest], + asset_service.AnalyzeMoveResponse]: + # 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._AnalyzeMove(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_org_policies(self) -> Callable[ + [asset_service.AnalyzeOrgPoliciesRequest], + asset_service.AnalyzeOrgPoliciesResponse]: + # 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._AnalyzeOrgPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_org_policy_governed_assets(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: + # 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._AnalyzeOrgPolicyGovernedAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def analyze_org_policy_governed_containers(self) -> Callable[ + [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], + asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: + # 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._AnalyzeOrgPolicyGovernedContainers(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_get_assets_history(self) -> Callable[ + [asset_service.BatchGetAssetsHistoryRequest], + asset_service.BatchGetAssetsHistoryResponse]: + # 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._BatchGetAssetsHistory(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_get_effective_iam_policies(self) -> Callable[ + [asset_service.BatchGetEffectiveIamPoliciesRequest], + asset_service.BatchGetEffectiveIamPoliciesResponse]: + # 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._BatchGetEffectiveIamPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + asset_service.Feed]: + # 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._CreateFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_saved_query(self) -> Callable[ + [asset_service.CreateSavedQueryRequest], + asset_service.SavedQuery]: + # 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._CreateSavedQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + 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._DeleteFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_saved_query(self) -> Callable[ + [asset_service.DeleteSavedQueryRequest], + 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._DeleteSavedQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_assets(self) -> Callable[ + [asset_service.ExportAssetsRequest], + 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._ExportAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + asset_service.Feed]: + # 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._GetFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_saved_query(self) -> Callable[ + [asset_service.GetSavedQueryRequest], + asset_service.SavedQuery]: + # 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._GetSavedQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + asset_service.ListAssetsResponse]: + # 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._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + asset_service.ListFeedsResponse]: + # 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._ListFeeds(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_saved_queries(self) -> Callable[ + [asset_service.ListSavedQueriesRequest], + asset_service.ListSavedQueriesResponse]: + # 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._ListSavedQueries(self._session, self._host, self._interceptor) # type: ignore + + @property + def query_assets(self) -> Callable[ + [asset_service.QueryAssetsRequest], + asset_service.QueryAssetsResponse]: + # 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._QueryAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse]: + # 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._SearchAllIamPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse]: + # 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._SearchAllResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + asset_service.Feed]: + # 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._UpdateFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_saved_query(self) -> Callable[ + [asset_service.UpdateSavedQueryRequest], + asset_service.SavedQuery]: + # 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._UpdateSavedQuery(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(AssetServiceRestStub): + 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=*/*/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 kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AssetServiceRestTransport', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py new file mode 100644 index 00000000..9819b55a --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py @@ -0,0 +1,180 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .asset_service import ( + AnalyzeIamPolicyLongrunningMetadata, + AnalyzeIamPolicyLongrunningRequest, + AnalyzeIamPolicyLongrunningResponse, + AnalyzeIamPolicyRequest, + AnalyzeIamPolicyResponse, + AnalyzeMoveRequest, + AnalyzeMoveResponse, + AnalyzeOrgPoliciesRequest, + AnalyzeOrgPoliciesResponse, + AnalyzeOrgPolicyGovernedAssetsRequest, + AnalyzeOrgPolicyGovernedAssetsResponse, + AnalyzeOrgPolicyGovernedContainersRequest, + AnalyzeOrgPolicyGovernedContainersResponse, + AnalyzerOrgPolicy, + AnalyzerOrgPolicyConstraint, + BatchGetAssetsHistoryRequest, + BatchGetAssetsHistoryResponse, + BatchGetEffectiveIamPoliciesRequest, + BatchGetEffectiveIamPoliciesResponse, + BigQueryDestination, + CreateFeedRequest, + CreateSavedQueryRequest, + DeleteFeedRequest, + DeleteSavedQueryRequest, + ExportAssetsRequest, + ExportAssetsResponse, + Feed, + FeedOutputConfig, + GcsDestination, + GcsOutputResult, + GetFeedRequest, + GetSavedQueryRequest, + IamPolicyAnalysisOutputConfig, + IamPolicyAnalysisQuery, + ListAssetsRequest, + ListAssetsResponse, + ListFeedsRequest, + ListFeedsResponse, + ListSavedQueriesRequest, + ListSavedQueriesResponse, + MoveAnalysis, + MoveAnalysisResult, + MoveImpact, + OutputConfig, + OutputResult, + PartitionSpec, + PubsubDestination, + QueryAssetsOutputConfig, + QueryAssetsRequest, + QueryAssetsResponse, + QueryResult, + SavedQuery, + SearchAllIamPoliciesRequest, + SearchAllIamPoliciesResponse, + SearchAllResourcesRequest, + SearchAllResourcesResponse, + TableFieldSchema, + TableSchema, + UpdateFeedRequest, + UpdateSavedQueryRequest, + ContentType, +) +from .assets import ( + Asset, + AttachedResource, + ConditionEvaluation, + EffectiveTagDetails, + IamPolicyAnalysisResult, + IamPolicyAnalysisState, + IamPolicySearchResult, + RelatedAsset, + RelatedAssets, + RelatedResource, + RelatedResources, + RelationshipAttributes, + Resource, + ResourceSearchResult, + Tag, + TemporalAsset, + TimeWindow, + VersionedResource, +) + +__all__ = ( + 'AnalyzeIamPolicyLongrunningMetadata', + 'AnalyzeIamPolicyLongrunningRequest', + 'AnalyzeIamPolicyLongrunningResponse', + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'AnalyzeMoveRequest', + 'AnalyzeMoveResponse', + 'AnalyzeOrgPoliciesRequest', + 'AnalyzeOrgPoliciesResponse', + 'AnalyzeOrgPolicyGovernedAssetsRequest', + 'AnalyzeOrgPolicyGovernedAssetsResponse', + 'AnalyzeOrgPolicyGovernedContainersRequest', + 'AnalyzeOrgPolicyGovernedContainersResponse', + 'AnalyzerOrgPolicy', + 'AnalyzerOrgPolicyConstraint', + 'BatchGetAssetsHistoryRequest', + 'BatchGetAssetsHistoryResponse', + 'BatchGetEffectiveIamPoliciesRequest', + 'BatchGetEffectiveIamPoliciesResponse', + 'BigQueryDestination', + 'CreateFeedRequest', + 'CreateSavedQueryRequest', + 'DeleteFeedRequest', + 'DeleteSavedQueryRequest', + 'ExportAssetsRequest', + 'ExportAssetsResponse', + 'Feed', + 'FeedOutputConfig', + 'GcsDestination', + 'GcsOutputResult', + 'GetFeedRequest', + 'GetSavedQueryRequest', + 'IamPolicyAnalysisOutputConfig', + 'IamPolicyAnalysisQuery', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'ListSavedQueriesRequest', + 'ListSavedQueriesResponse', + 'MoveAnalysis', + 'MoveAnalysisResult', + 'MoveImpact', + 'OutputConfig', + 'OutputResult', + 'PartitionSpec', + 'PubsubDestination', + 'QueryAssetsOutputConfig', + 'QueryAssetsRequest', + 'QueryAssetsResponse', + 'QueryResult', + 'SavedQuery', + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'TableFieldSchema', + 'TableSchema', + 'UpdateFeedRequest', + 'UpdateSavedQueryRequest', + 'ContentType', + 'Asset', + 'AttachedResource', + 'ConditionEvaluation', + 'EffectiveTagDetails', + 'IamPolicyAnalysisResult', + 'IamPolicyAnalysisState', + 'IamPolicySearchResult', + 'RelatedAsset', + 'RelatedAssets', + 'RelatedResource', + 'RelatedResources', + 'RelationshipAttributes', + 'Resource', + 'ResourceSearchResult', + 'Tag', + 'TemporalAsset', + 'TimeWindow', + 'VersionedResource', +) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py b/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py new file mode 100644 index 00000000..bc8a0318 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py @@ -0,0 +1,4036 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.asset_v1.types import assets as gca_assets +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1', + manifest={ + 'ContentType', + 'AnalyzeIamPolicyLongrunningMetadata', + 'ExportAssetsRequest', + 'ExportAssetsResponse', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'BatchGetAssetsHistoryRequest', + 'BatchGetAssetsHistoryResponse', + 'CreateFeedRequest', + 'GetFeedRequest', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'UpdateFeedRequest', + 'DeleteFeedRequest', + 'OutputConfig', + 'OutputResult', + 'GcsOutputResult', + 'GcsDestination', + 'BigQueryDestination', + 'PartitionSpec', + 'PubsubDestination', + 'FeedOutputConfig', + 'Feed', + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + 'IamPolicyAnalysisQuery', + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'IamPolicyAnalysisOutputConfig', + 'AnalyzeIamPolicyLongrunningRequest', + 'AnalyzeIamPolicyLongrunningResponse', + 'SavedQuery', + 'CreateSavedQueryRequest', + 'GetSavedQueryRequest', + 'ListSavedQueriesRequest', + 'ListSavedQueriesResponse', + 'UpdateSavedQueryRequest', + 'DeleteSavedQueryRequest', + 'AnalyzeMoveRequest', + 'AnalyzeMoveResponse', + 'MoveAnalysis', + 'MoveAnalysisResult', + 'MoveImpact', + 'QueryAssetsOutputConfig', + 'QueryAssetsRequest', + 'QueryAssetsResponse', + 'QueryResult', + 'TableSchema', + 'TableFieldSchema', + 'BatchGetEffectiveIamPoliciesRequest', + 'BatchGetEffectiveIamPoliciesResponse', + 'AnalyzerOrgPolicy', + 'AnalyzerOrgPolicyConstraint', + 'AnalyzeOrgPoliciesRequest', + 'AnalyzeOrgPoliciesResponse', + 'AnalyzeOrgPolicyGovernedContainersRequest', + 'AnalyzeOrgPolicyGovernedContainersResponse', + 'AnalyzeOrgPolicyGovernedAssetsRequest', + 'AnalyzeOrgPolicyGovernedAssetsResponse', + }, +) + + +class ContentType(proto.Enum): + r"""Asset content type. + + Values: + CONTENT_TYPE_UNSPECIFIED (0): + Unspecified content type. + RESOURCE (1): + Resource metadata. + IAM_POLICY (2): + The actual IAM policy set on a resource. + ORG_POLICY (4): + The organization policy set on an asset. + ACCESS_POLICY (5): + The Access Context Manager policy set on an + asset. + OS_INVENTORY (6): + The runtime OS Inventory information. + RELATIONSHIP (7): + The related resources. + """ + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + ORG_POLICY = 4 + ACCESS_POLICY = 5 + OS_INVENTORY = 6 + RELATIONSHIP = 7 + + +class AnalyzeIamPolicyLongrunningMetadata(proto.Message): + r"""Represents the metadata of the longrunning operation for the + AnalyzeIamPolicyLongrunning RPC. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +class ExportAssetsRequest(proto.Message): + r"""Export asset request. + + Attributes: + parent (str): + Required. The relative name of the root + asset. This can only be an organization number + (such as "organizations/123"), a project ID + (such as "projects/my-project-id"), or a project + number (such as "projects/12345"), or a folder + number (such as "folders/123"). + read_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp to take an asset snapshot. This can + only be set to a timestamp between the current + time and the current time minus 35 days + (inclusive). If not specified, the current time + will be used. Due to delays in resource data + collection and indexing, there is a volatile + window during which running the same query may + get different results. + asset_types (MutableSequence[str]): + A list of asset types to take a snapshot for. For example: + "compute.googleapis.com/Disk". + + Regular expressions are also supported. For example: + + - "compute.googleapis.com.*" snapshots resources whose + asset type starts with "compute.googleapis.com". + - ".*Instance" snapshots resources whose asset type ends + with "Instance". + - ".*Instance.*" snapshots resources whose asset type + contains "Instance". + + See `RE2 `__ for + all supported regular expression syntax. If the regular + expression does not match any supported asset type, an + INVALID_ARGUMENT error will be returned. + + If specified, only matching assets will be returned, + otherwise, it will snapshot all asset types. See + `Introduction to Cloud Asset + Inventory `__ + for all supported asset types. + content_type (google.cloud.asset_v1.types.ContentType): + Asset content type. If not specified, no + content but the asset name will be returned. + output_config (google.cloud.asset_v1.types.OutputConfig): + Required. Output configuration indicating + where the results will be output to. + relationship_types (MutableSequence[str]): + A list of relationship types to export, for example: + ``INSTANCE_TO_INSTANCEGROUP``. This field should only be + specified if content_type=RELATIONSHIP. + + - If specified: it snapshots specified relationships. It + returns an error if any of the [relationship_types] + doesn't belong to the supported relationship types of the + [asset_types] or if any of the [asset_types] doesn't + belong to the source types of the [relationship_types]. + - Otherwise: it snapshots the supported relationships for + all [asset_types] or returns an error if any of the + [asset_types] has no relationship support. An unspecified + asset types field means all supported asset_types. See + `Introduction to Cloud Asset + Inventory `__ + for all supported asset types and relationship types. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type: 'ContentType' = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + output_config: 'OutputConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='OutputConfig', + ) + relationship_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class ExportAssetsResponse(proto.Message): + r"""The export asset response. This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + Attributes: + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time the snapshot was taken. + output_config (google.cloud.asset_v1.types.OutputConfig): + Output configuration indicating where the + results were output to. + output_result (google.cloud.asset_v1.types.OutputResult): + Output result indicating where the assets were exported to. + For example, a set of actual Cloud Storage object URIs where + the assets are exported to. The URIs can be different from + what [output_config] has specified, as the service will + split the output object into multiple ones once it exceeds a + single Cloud Storage object limit. + """ + + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + output_config: 'OutputConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='OutputConfig', + ) + output_result: 'OutputResult' = proto.Field( + proto.MESSAGE, + number=3, + message='OutputResult', + ) + + +class ListAssetsRequest(proto.Message): + r"""ListAssets request. + + Attributes: + parent (str): + Required. Name of the organization, folder, or project the + assets belong to. Format: + "organizations/[organization-number]" (such as + "organizations/123"), "projects/[project-id]" (such as + "projects/my-project-id"), "projects/[project-number]" (such + as "projects/12345"), or "folders/[folder-number]" (such as + "folders/12345"). + read_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp to take an asset snapshot. This can + only be set to a timestamp between the current + time and the current time minus 35 days + (inclusive). If not specified, the current time + will be used. Due to delays in resource data + collection and indexing, there is a volatile + window during which running the same query may + get different results. + asset_types (MutableSequence[str]): + A list of asset types to take a snapshot for. For example: + "compute.googleapis.com/Disk". + + Regular expression is also supported. For example: + + - "compute.googleapis.com.*" snapshots resources whose + asset type starts with "compute.googleapis.com". + - ".*Instance" snapshots resources whose asset type ends + with "Instance". + - ".*Instance.*" snapshots resources whose asset type + contains "Instance". + + See `RE2 `__ for + all supported regular expression syntax. If the regular + expression does not match any supported asset type, an + INVALID_ARGUMENT error will be returned. + + If specified, only matching assets will be returned, + otherwise, it will snapshot all asset types. See + `Introduction to Cloud Asset + Inventory `__ + for all supported asset types. + content_type (google.cloud.asset_v1.types.ContentType): + Asset content type. If not specified, no + content but the asset name will be returned. + page_size (int): + The maximum number of assets to be returned + in a single response. Default is 100, minimum is + 1, and maximum is 1000. + page_token (str): + The ``next_page_token`` returned from the previous + ``ListAssetsResponse``, or unspecified for the first + ``ListAssetsRequest``. It is a continuation of a prior + ``ListAssets`` call, and the API should return the next page + of assets. + relationship_types (MutableSequence[str]): + A list of relationship types to output, for example: + ``INSTANCE_TO_INSTANCEGROUP``. This field should only be + specified if content_type=RELATIONSHIP. + + - If specified: it snapshots specified relationships. It + returns an error if any of the [relationship_types] + doesn't belong to the supported relationship types of the + [asset_types] or if any of the [asset_types] doesn't + belong to the source types of the [relationship_types]. + - Otherwise: it snapshots the supported relationships for + all [asset_types] or returns an error if any of the + [asset_types] has no relationship support. An unspecified + asset types field means all supported asset_types. See + `Introduction to Cloud Asset + Inventory `__ + for all supported asset types and relationship types. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type: 'ContentType' = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + page_size: int = proto.Field( + proto.INT32, + number=5, + ) + page_token: str = proto.Field( + proto.STRING, + number=6, + ) + relationship_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class ListAssetsResponse(proto.Message): + r"""ListAssets response. + + Attributes: + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time the snapshot was taken. + assets (MutableSequence[google.cloud.asset_v1.types.Asset]): + Assets. + next_page_token (str): + Token to retrieve the next page of results. + It expires 72 hours after the page token for the + first page is generated. Set to empty if there + are no remaining results. + """ + + @property + def raw_page(self): + return self + + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + assets: MutableSequence[gca_assets.Asset] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gca_assets.Asset, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class BatchGetAssetsHistoryRequest(proto.Message): + r"""Batch get assets history request. + + Attributes: + parent (str): + Required. The relative name of the root + asset. It can only be an organization number + (such as "organizations/123"), a project ID + (such as "projects/my-project-id")", or a + project number (such as "projects/12345"). + asset_names (MutableSequence[str]): + A list of the full names of the assets. See: + https://cloud.google.com/asset-inventory/docs/resource-name-format + Example: + + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + + The request becomes a no-op if the asset name list is empty, + and the max size of the asset name list is 100 in one + request. + content_type (google.cloud.asset_v1.types.ContentType): + Optional. The content type. + read_time_window (google.cloud.asset_v1.types.TimeWindow): + Optional. The time window for the asset history. Both + start_time and end_time are optional and if set, it must be + after the current time minus 35 days. If end_time is not + set, it is default to current timestamp. If start_time is + not set, the snapshot of the assets at end_time will be + returned. The returned results contain all temporal assets + whose time window overlap with read_time_window. + relationship_types (MutableSequence[str]): + Optional. A list of relationship types to output, for + example: ``INSTANCE_TO_INSTANCEGROUP``. This field should + only be specified if content_type=RELATIONSHIP. + + - If specified: it outputs specified relationships' history + on the [asset_names]. It returns an error if any of the + [relationship_types] doesn't belong to the supported + relationship types of the [asset_names] or if any of the + [asset_names]'s types doesn't belong to the source types + of the [relationship_types]. + - Otherwise: it outputs the supported relationships' + history on the [asset_names] or returns an error if any + of the [asset_names]'s types has no relationship support. + See `Introduction to Cloud Asset + Inventory `__ + for all supported asset types and relationship types. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + asset_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + content_type: 'ContentType' = proto.Field( + proto.ENUM, + number=3, + enum='ContentType', + ) + read_time_window: gca_assets.TimeWindow = proto.Field( + proto.MESSAGE, + number=4, + message=gca_assets.TimeWindow, + ) + relationship_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class BatchGetAssetsHistoryResponse(proto.Message): + r"""Batch get assets history response. + + Attributes: + assets (MutableSequence[google.cloud.asset_v1.types.TemporalAsset]): + A list of assets with valid time windows. + """ + + assets: MutableSequence[gca_assets.TemporalAsset] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gca_assets.TemporalAsset, + ) + + +class CreateFeedRequest(proto.Message): + r"""Create asset feed request. + + Attributes: + parent (str): + Required. The name of the + project/folder/organization where this feed + should be created in. It can only be an + organization number (such as + "organizations/123"), a folder number (such as + "folders/123"), a project ID (such as + "projects/my-project-id"), or a project number + (such as "projects/12345"). + feed_id (str): + Required. This is the client-assigned asset + feed identifier and it needs to be unique under + a specific parent project/folder/organization. + feed (google.cloud.asset_v1.types.Feed): + Required. The feed details. The field ``name`` must be empty + and it will be generated in the format of: + projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + feed_id: str = proto.Field( + proto.STRING, + number=2, + ) + feed: 'Feed' = proto.Field( + proto.MESSAGE, + number=3, + message='Feed', + ) + + +class GetFeedRequest(proto.Message): + r"""Get asset feed request. + + Attributes: + name (str): + Required. The name of the Feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFeedsRequest(proto.Message): + r"""List asset feeds request. + + Attributes: + parent (str): + Required. The parent + project/folder/organization whose feeds are to + be listed. It can only be using + project/folder/organization number (such as + "folders/12345")", or a project ID (such as + "projects/my-project-id"). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFeedsResponse(proto.Message): + r""" + + Attributes: + feeds (MutableSequence[google.cloud.asset_v1.types.Feed]): + A list of feeds. + """ + + feeds: MutableSequence['Feed'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Feed', + ) + + +class UpdateFeedRequest(proto.Message): + r"""Update asset feed request. + + Attributes: + feed (google.cloud.asset_v1.types.Feed): + Required. The new values of feed details. It must match an + existing feed and the field ``name`` must be in the format + of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Only updates the ``feed`` fields indicated by this + mask. The field mask must not be empty, and it must not + contain fields that are immutable or only set by the server. + """ + + feed: 'Feed' = proto.Field( + proto.MESSAGE, + number=1, + message='Feed', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteFeedRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OutputConfig(proto.Message): + r"""Output configuration for export assets destination. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_destination (google.cloud.asset_v1.types.GcsDestination): + Destination on Cloud Storage. + + This field is a member of `oneof`_ ``destination``. + bigquery_destination (google.cloud.asset_v1.types.BigQueryDestination): + Destination on BigQuery. The output table + stores the fields in asset Protobuf as columns + in BigQuery. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_destination: 'GcsDestination' = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + bigquery_destination: 'BigQueryDestination' = proto.Field( + proto.MESSAGE, + number=2, + oneof='destination', + message='BigQueryDestination', + ) + + +class OutputResult(proto.Message): + r"""Output result of export assets. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_result (google.cloud.asset_v1.types.GcsOutputResult): + Export result on Cloud Storage. + + This field is a member of `oneof`_ ``result``. + """ + + gcs_result: 'GcsOutputResult' = proto.Field( + proto.MESSAGE, + number=1, + oneof='result', + message='GcsOutputResult', + ) + + +class GcsOutputResult(proto.Message): + r"""A Cloud Storage output result. + + Attributes: + uris (MutableSequence[str]): + List of URIs of the Cloud Storage objects. Example: + "gs://bucket_name/object_name". + """ + + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class GcsDestination(proto.Message): + r"""A Cloud Storage location. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + The URI of the Cloud Storage object. It's the same URI that + is used by gsutil. Example: "gs://bucket_name/object_name". + See `Viewing and Editing Object + Metadata `__ + for more information. + + If the specified Cloud Storage object already exists and + there is no + `hold `__, + it will be overwritten with the exported result. + + This field is a member of `oneof`_ ``object_uri``. + uri_prefix (str): + The URI prefix of all generated Cloud Storage objects. + Example: "gs://bucket_name/object_name_prefix". Each object + URI is in format: "gs://bucket_name/object_name_prefix// and + only contains assets for that type. starts from 0. Example: + "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" + is the first shard of output objects containing all + compute.googleapis.com/Disk assets. An INVALID_ARGUMENT + error will be returned if file with the same name + "gs://bucket_name/object_name_prefix" already exists. + + This field is a member of `oneof`_ ``object_uri``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + oneof='object_uri', + ) + uri_prefix: str = proto.Field( + proto.STRING, + number=2, + oneof='object_uri', + ) + + +class BigQueryDestination(proto.Message): + r"""A BigQuery destination for exporting assets to. + + Attributes: + dataset (str): + Required. The BigQuery dataset in format + "projects/projectId/datasets/datasetId", to which the + snapshot result should be exported. If this dataset does not + exist, the export call returns an INVALID_ARGUMENT error. + Setting the ``contentType`` for ``exportAssets`` determines + the + `schema `__ + of the BigQuery table. Setting + ``separateTablesPerAssetType`` to ``TRUE`` also influences + the schema. + table (str): + Required. The BigQuery table to which the + snapshot result should be written. If this table + does not exist, a new table with the given name + will be created. + force (bool): + If the destination table already exists and this flag is + ``TRUE``, the table will be overwritten by the contents of + assets snapshot. If the flag is ``FALSE`` or unset and the + destination table already exists, the export call returns an + INVALID_ARGUMEMT error. + partition_spec (google.cloud.asset_v1.types.PartitionSpec): + [partition_spec] determines whether to export to partitioned + table(s) and how to partition the data. + + If [partition_spec] is unset or + [partition_spec.partition_key] is unset or + ``PARTITION_KEY_UNSPECIFIED``, the snapshot results will be + exported to non-partitioned table(s). [force] will decide + whether to overwrite existing table(s). + + If [partition_spec] is specified. First, the snapshot + results will be written to partitioned table(s) with two + additional timestamp columns, readTime and requestTime, one + of which will be the partition key. Secondly, in the case + when any destination table already exists, it will first try + to update existing table's schema as necessary by appending + additional columns. Then, if [force] is ``TRUE``, the + corresponding partition will be overwritten by the snapshot + results (data in different partitions will remain intact); + if [force] is unset or ``FALSE``, it will append the data. + An error will be returned if the schema update or data + appension fails. + separate_tables_per_asset_type (bool): + If this flag is ``TRUE``, the snapshot results will be + written to one or multiple tables, each of which contains + results of one asset type. The [force] and [partition_spec] + fields will apply to each of them. + + Field [table] will be concatenated with "*" and the asset + type names (see + https://cloud.google.com/asset-inventory/docs/supported-asset-types + for supported asset types) to construct per-asset-type table + names, in which all non-alphanumeric characters like "." and + "/" will be substituted by "*". Example: if field [table] is + "mytable" and snapshot results contain + "storage.googleapis.com/Bucket" assets, the corresponding + table name will be "mytable_storage_googleapis_com_Bucket". + If any of these tables does not exist, a new table with the + concatenated name will be created. + + When [content_type] in the ExportAssetsRequest is + ``RESOURCE``, the schema of each table will include + RECORD-type columns mapped to the nested fields in the + Asset.resource.data field of that asset type (up to the 15 + nested level BigQuery supports + (https://cloud.google.com/bigquery/docs/nested-repeated#limitations)). + The fields in >15 nested levels will be stored in JSON + format string as a child column of its parent RECORD column. + + If error occurs when exporting to any table, the whole + export call will return an error but the export results that + already succeed will persist. Example: if exporting to + table_type_A succeeds when exporting to table_type_B fails + during one export call, the results in table_type_A will + persist and there will not be partial results persisting in + a table. + """ + + dataset: str = proto.Field( + proto.STRING, + number=1, + ) + table: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + partition_spec: 'PartitionSpec' = proto.Field( + proto.MESSAGE, + number=4, + message='PartitionSpec', + ) + separate_tables_per_asset_type: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class PartitionSpec(proto.Message): + r"""Specifications of BigQuery partitioned table as export + destination. + + Attributes: + partition_key (google.cloud.asset_v1.types.PartitionSpec.PartitionKey): + The partition key for BigQuery partitioned + table. + """ + class PartitionKey(proto.Enum): + r"""This enum is used to determine the partition key column when + exporting assets to BigQuery partitioned table(s). Note that, if the + partition key is a timestamp column, the actual partition is based + on its date value (expressed in UTC. see details in + https://cloud.google.com/bigquery/docs/partitioned-tables#date_timestamp_partitioned_tables). + + Values: + PARTITION_KEY_UNSPECIFIED (0): + Unspecified partition key. If used, it means + using non-partitioned table. + READ_TIME (1): + The time when the snapshot is taken. If specified as + partition key, the result table(s) is partitoned by the + additional timestamp column, readTime. If [read_time] in + ExportAssetsRequest is specified, the readTime column's + value will be the same as it. Otherwise, its value will be + the current time that is used to take the snapshot. + REQUEST_TIME (2): + The time when the request is received and + started to be processed. If specified as + partition key, the result table(s) is partitoned + by the requestTime column, an additional + timestamp column representing when the request + was received. + """ + PARTITION_KEY_UNSPECIFIED = 0 + READ_TIME = 1 + REQUEST_TIME = 2 + + partition_key: PartitionKey = proto.Field( + proto.ENUM, + number=1, + enum=PartitionKey, + ) + + +class PubsubDestination(proto.Message): + r"""A Pub/Sub destination. + + Attributes: + topic (str): + The name of the Pub/Sub topic to publish to. Example: + ``projects/PROJECT_ID/topics/TOPIC_ID``. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FeedOutputConfig(proto.Message): + r"""Output configuration for asset feed destination. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pubsub_destination (google.cloud.asset_v1.types.PubsubDestination): + Destination on Pub/Sub. + + This field is a member of `oneof`_ ``destination``. + """ + + pubsub_destination: 'PubsubDestination' = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='PubsubDestination', + ) + + +class Feed(proto.Message): + r"""An asset feed used to export asset updates to a destinations. + An asset feed filter controls what updates are exported. The + asset feed must be created within a project, organization, or + folder. Supported destinations are: + + Pub/Sub topics. + + Attributes: + name (str): + Required. The format will be + projects/{project_number}/feeds/{client-assigned_feed_identifier} + or + folders/{folder_number}/feeds/{client-assigned_feed_identifier} + or + organizations/{organization_number}/feeds/{client-assigned_feed_identifier} + + The client-assigned feed identifier must be unique within + the parent project/folder/organization. + asset_names (MutableSequence[str]): + A list of the full names of the assets to receive updates. + You must specify either or both of asset_names and + asset_types. Only asset updates matching specified + asset_names or asset_types are exported to the feed. + Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + For a list of the full names for supported asset types, see + `Resource name + format `__. + asset_types (MutableSequence[str]): + A list of types of the assets to receive updates. You must + specify either or both of asset_names and asset_types. Only + asset updates matching specified asset_names or asset_types + are exported to the feed. Example: + ``"compute.googleapis.com/Disk"`` + + For a list of all supported asset types, see `Supported + asset + types `__. + content_type (google.cloud.asset_v1.types.ContentType): + Asset content type. If not specified, no + content but the asset name and type will be + returned. + feed_output_config (google.cloud.asset_v1.types.FeedOutputConfig): + Required. Feed output configuration defining + where the asset updates are published to. + condition (google.type.expr_pb2.Expr): + A condition which determines whether an asset update should + be published. If specified, an asset will be returned only + when the expression evaluates to true. When set, + ``expression`` field in the ``Expr`` must be a valid [CEL + expression] (https://github.com/google/cel-spec) on a + TemporalAsset with name ``temporal_asset``. Example: a Feed + with expression ("temporal_asset.deleted == true") will only + publish Asset deletions. Other fields of ``Expr`` are + optional. + + See our `user + guide `__ + for detailed instructions. + relationship_types (MutableSequence[str]): + A list of relationship types to output, for example: + ``INSTANCE_TO_INSTANCEGROUP``. This field should only be + specified if content_type=RELATIONSHIP. + + - If specified: it outputs specified relationship updates + on the [asset_names] or the [asset_types]. It returns an + error if any of the [relationship_types] doesn't belong + to the supported relationship types of the [asset_names] + or [asset_types], or any of the [asset_names] or the + [asset_types] doesn't belong to the source types of the + [relationship_types]. + - Otherwise: it outputs the supported relationships of the + types of [asset_names] and [asset_types] or returns an + error if any of the [asset_names] or the [asset_types] + has no replationship support. See `Introduction to Cloud + Asset + Inventory `__ + for all supported asset types and relationship types. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type: 'ContentType' = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + feed_output_config: 'FeedOutputConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='FeedOutputConfig', + ) + condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=6, + message=expr_pb2.Expr, + ) + relationship_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + +class SearchAllResourcesRequest(proto.Message): + r"""Search all resources request. + + Attributes: + scope (str): + Required. A scope can be a project, a folder, or an + organization. The search is limited to the resources within + the ``scope``. The caller must be granted the + ```cloudasset.assets.searchAllResources`` `__ + permission on the desired scope. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + query (str): + Optional. The query statement. See `how to construct a + query `__ + for more information. If not specified or empty, it will + search all the resources within the specified ``scope``. + + Examples: + + - ``name:Important`` to find Google Cloud resources whose + name contains ``Important`` as a word. + - ``name=Important`` to find the Google Cloud resource + whose name is exactly ``Important``. + - ``displayName:Impor*`` to find Google Cloud resources + whose display name contains ``Impor`` as a prefix of any + word in the field. + - ``location:us-west*`` to find Google Cloud resources + whose location contains both ``us`` and ``west`` as + prefixes. + - ``labels:prod`` to find Google Cloud resources whose + labels contain ``prod`` as a key or value. + - ``labels.env:prod`` to find Google Cloud resources that + have a label ``env`` and its value is ``prod``. + - ``labels.env:*`` to find Google Cloud resources that have + a label ``env``. + - ``tagKeys:env`` to find Google Cloud resources that have + directly attached tags where the + ```TagKey`` `__ + .\ ``namespacedName`` contains ``env``. + - ``tagValues:prod*`` to find Google Cloud resources that + have directly attached tags where the + ```TagValue`` `__ + .\ ``namespacedName`` contains a word prefixed by + ``prod``. + - ``tagValueIds=tagValues/123`` to find Google Cloud + resources that have directly attached tags where the + ```TagValue`` `__ + .\ ``name`` is exactly ``tagValues/123``. + - ``effectiveTagKeys:env`` to find Google Cloud resources + that have directly attached or inherited tags where the + ```TagKey`` `__ + .\ ``namespacedName`` contains ``env``. + - ``effectiveTagValues:prod*`` to find Google Cloud + resources that have directly attached or inherited tags + where the + ```TagValue`` `__ + .\ ``namespacedName`` contains a word prefixed by + ``prod``. + - ``effectiveTagValueIds=tagValues/123`` to find Google + Cloud resources that have directly attached or inherited + tags where the + ```TagValue`` `__ + .\ ``name`` is exactly ``tagValues/123``. + - ``kmsKey:key`` to find Google Cloud resources encrypted + with a customer-managed encryption key whose name + contains ``key`` as a word. This field is deprecated. + Please use the ``kmsKeys`` field to retrieve Cloud KMS + key information. + - ``kmsKeys:key`` to find Google Cloud resources encrypted + with customer-managed encryption keys whose name contains + the word ``key``. + - ``relationships:instance-group-1`` to find Google Cloud + resources that have relationships with + ``instance-group-1`` in the related resource name. + - ``relationships:INSTANCE_TO_INSTANCEGROUP`` to find + Compute Engine instances that have relationships of type + ``INSTANCE_TO_INSTANCEGROUP``. + - ``relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1`` + to find Compute Engine instances that have relationships + with ``instance-group-1`` in the Compute Engine instance + group resource name, for relationship type + ``INSTANCE_TO_INSTANCEGROUP``. + - ``state:ACTIVE`` to find Google Cloud resources whose + state contains ``ACTIVE`` as a word. + - ``NOT state:ACTIVE`` to find Google Cloud resources whose + state doesn't contain ``ACTIVE`` as a word. + - ``createTime<1609459200`` to find Google Cloud resources + that were created before ``2021-01-01 00:00:00 UTC``. + ``1609459200`` is the epoch timestamp of + ``2021-01-01 00:00:00 UTC`` in seconds. + - ``updateTime>1609459200`` to find Google Cloud resources + that were updated after ``2021-01-01 00:00:00 UTC``. + ``1609459200`` is the epoch timestamp of + ``2021-01-01 00:00:00 UTC`` in seconds. + - ``Important`` to find Google Cloud resources that contain + ``Important`` as a word in any of the searchable fields. + - ``Impor*`` to find Google Cloud resources that contain + ``Impor`` as a prefix of any word in any of the + searchable fields. + - ``Important location:(us-west1 OR global)`` to find + Google Cloud resources that contain ``Important`` as a + word in any of the searchable fields and are also located + in the ``us-west1`` region or the ``global`` location. + asset_types (MutableSequence[str]): + Optional. A list of asset types that this request searches + for. If empty, it will search all the `searchable asset + types `__. + + Regular expressions are also supported. For example: + + - "compute.googleapis.com.*" snapshots resources whose + asset type starts with "compute.googleapis.com". + - ".*Instance" snapshots resources whose asset type ends + with "Instance". + - ".*Instance.*" snapshots resources whose asset type + contains "Instance". + + See `RE2 `__ for + all supported regular expression syntax. If the regular + expression does not match any supported asset type, an + INVALID_ARGUMENT error will be returned. + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero or a negative value, server will pick an + appropriate default. Returned results may be fewer than + requested. When this happens, there could be more results as + long as ``next_page_token`` is returned. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``page_token`` must be the value of ``next_page_token`` from + the previous response. The values of all other method + parameters, must be identical to those in the previous call. + order_by (str): + Optional. A comma-separated list of fields specifying the + sorting order of the results. The default order is + ascending. Add " DESC" after the field name to indicate + descending order. Redundant space characters are ignored. + Example: "location DESC, name". Only the following fields in + the response are sortable: + + - name + - assetType + - project + - displayName + - description + - location + - createTime + - updateTime + - state + - parentFullResourceName + - parentAssetType + read_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. A comma-separated list of fields that you want + returned in the results. The following fields are returned + by default if not specified: + + - ``name`` + - ``assetType`` + - ``project`` + - ``folders`` + - ``organization`` + - ``displayName`` + - ``description`` + - ``location`` + - ``labels`` + - ``tags`` + - ``effectiveTags`` + - ``networkTags`` + - ``kmsKeys`` + - ``createTime`` + - ``updateTime`` + - ``state`` + - ``additionalAttributes`` + - ``parentFullResourceName`` + - ``parentAssetType`` + + Some fields of large size, such as ``versionedResources``, + ``attachedResources``, ``effectiveTags`` etc., are not + returned by default, but you can specify them in the + ``read_mask`` parameter if you want to include them. If + ``"*"`` is specified, all `available + fields `__ + are returned. Examples: ``"name,location"``, + ``"name,versionedResources"``, ``"*"``. Any invalid field + path will trigger INVALID_ARGUMENT error. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + read_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=8, + message=field_mask_pb2.FieldMask, + ) + + +class SearchAllResourcesResponse(proto.Message): + r"""Search all resources response. + + Attributes: + results (MutableSequence[google.cloud.asset_v1.types.ResourceSearchResult]): + A list of Resources that match the search + query. It contains the resource standard + metadata information. + next_page_token (str): + If there are more results than those appearing in this + response, then ``next_page_token`` is included. To get the + next set of results, call this method again using the value + of ``next_page_token`` as ``page_token``. + """ + + @property + def raw_page(self): + return self + + results: MutableSequence[gca_assets.ResourceSearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gca_assets.ResourceSearchResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchAllIamPoliciesRequest(proto.Message): + r"""Search all IAM policies request. + + Attributes: + scope (str): + Required. A scope can be a project, a folder, or an + organization. The search is limited to the IAM policies + within the ``scope``. The caller must be granted the + ```cloudasset.assets.searchAllIamPolicies`` `__ + permission on the desired scope. + + The allowed values are: + + - projects/{PROJECT_ID} (e.g., "projects/foo-bar") + - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") + - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + query (str): + Optional. The query statement. See `how to construct a + query `__ + for more information. If not specified or empty, it will + search all the IAM policies within the specified ``scope``. + Note that the query string is compared against each IAM + policy binding, including its principals, roles, and IAM + conditions. The returned IAM policies will only contain the + bindings that match your query. To learn more about the IAM + policy structure, see the `IAM policy + documentation `__. + + Examples: + + - ``policy:amy@gmail.com`` to find IAM policy bindings that + specify user "amy@gmail.com". + - ``policy:roles/compute.admin`` to find IAM policy + bindings that specify the Compute Admin role. + - ``policy:comp*`` to find IAM policy bindings that contain + "comp" as a prefix of any word in the binding. + - ``policy.role.permissions:storage.buckets.update`` to + find IAM policy bindings that specify a role containing + "storage.buckets.update" permission. Note that if callers + don't have ``iam.roles.get`` access to a role's included + permissions, policy bindings that specify this role will + be dropped from the search results. + - ``policy.role.permissions:upd*`` to find IAM policy + bindings that specify a role containing "upd" as a prefix + of any word in the role permission. Note that if callers + don't have ``iam.roles.get`` access to a role's included + permissions, policy bindings that specify this role will + be dropped from the search results. + - ``resource:organizations/123456`` to find IAM policy + bindings that are set on "organizations/123456". + - ``resource=//cloudresourcemanager.googleapis.com/projects/myproject`` + to find IAM policy bindings that are set on the project + named "myproject". + - ``Important`` to find IAM policy bindings that contain + "Important" as a word in any of the searchable fields + (except for the included permissions). + - ``resource:(instance1 OR instance2) policy:amy`` to find + IAM policy bindings that are set on resources "instance1" + or "instance2" and also specify user "amy". + - ``roles:roles/compute.admin`` to find IAM policy bindings + that specify the Compute Admin role. + - ``memberTypes:user`` to find IAM policy bindings that + contain the principal type "user". + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero or a negative value, server will pick an + appropriate default. Returned results may be fewer than + requested. When this happens, there could be more results as + long as ``next_page_token`` is returned. + page_token (str): + Optional. If present, retrieve the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of all other method parameters must be + identical to those in the previous call. + asset_types (MutableSequence[str]): + Optional. A list of asset types that the IAM policies are + attached to. If empty, it will search the IAM policies that + are attached to all the `searchable asset + types `__. + + Regular expressions are also supported. For example: + + - "compute.googleapis.com.*" snapshots IAM policies + attached to asset type starts with + "compute.googleapis.com". + - ".*Instance" snapshots IAM policies attached to asset + type ends with "Instance". + - ".*Instance.*" snapshots IAM policies attached to asset + type contains "Instance". + + See `RE2 `__ for + all supported regular expression syntax. If the regular + expression does not match any supported asset type, an + INVALID_ARGUMENT error will be returned. + order_by (str): + Optional. A comma-separated list of fields specifying the + sorting order of the results. The default order is + ascending. Add " DESC" after the field name to indicate + descending order. Redundant space characters are ignored. + Example: "assetType DESC, resource". Only singular primitive + fields in the response are sortable: + + - resource + - assetType + - project All the other fields such as repeated fields + (e.g., ``folders``) and non-primitive fields (e.g., + ``policy``) are not supported. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=7, + ) + + +class SearchAllIamPoliciesResponse(proto.Message): + r"""Search all IAM policies response. + + Attributes: + results (MutableSequence[google.cloud.asset_v1.types.IamPolicySearchResult]): + A list of IAM policies that match the search + query. Related information such as the + associated resource is returned along with the + policy. + next_page_token (str): + Set if there are more results than those appearing in this + response; to get the next set of results, call this method + again, using this value as the ``page_token``. + """ + + @property + def raw_page(self): + return self + + results: MutableSequence[gca_assets.IamPolicySearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gca_assets.IamPolicySearchResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class IamPolicyAnalysisQuery(proto.Message): + r"""IAM policy analysis query message. + + Attributes: + scope (str): + Required. The relative name of the root asset. Only + resources and IAM policies within the scope will be + analyzed. + + This can only be an organization number (such as + "organizations/123"), a folder number (such as + "folders/123"), a project ID (such as + "projects/my-project-id"), or a project number (such as + "projects/12345"). + + To know how to get organization id, visit + `here `__. + + To know how to get folder or project id, visit + `here `__. + resource_selector (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.ResourceSelector): + Optional. Specifies a resource for analysis. + identity_selector (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.IdentitySelector): + Optional. Specifies an identity for analysis. + access_selector (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.AccessSelector): + Optional. Specifies roles or permissions for + analysis. This is optional. + options (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.Options): + Optional. The query options. + condition_context (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.ConditionContext): + Optional. The hypothetical context for IAM + conditions evaluation. + """ + + class ResourceSelector(proto.Message): + r"""Specifies the resource to analyze for access policies, which + may be set directly on the resource, or on ancestors such as + organizations, folders or projects. + + Attributes: + full_resource_name (str): + Required. The [full resource name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of a resource of `supported resource + types `__. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class IdentitySelector(proto.Message): + r"""Specifies an identity for which to determine resource access, + based on roles assigned either directly to them or to the groups + they belong to, directly or indirectly. + + Attributes: + identity (str): + Required. The identity appear in the form of principals in + `IAM policy + binding `__. + + The examples of supported forms are: + "user:mike@example.com", "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com". + + Notice that wildcard characters (such as \* and ?) are not + supported. You must give a specific identity. + """ + + identity: str = proto.Field( + proto.STRING, + number=1, + ) + + class AccessSelector(proto.Message): + r"""Specifies roles and/or permissions to analyze, to determine + both the identities possessing them and the resources they + control. If multiple values are specified, results will include + roles or permissions matching any of them. The total number of + roles and permissions should be equal or less than 10. + + Attributes: + roles (MutableSequence[str]): + Optional. The roles to appear in result. + permissions (MutableSequence[str]): + Optional. The permissions to appear in + result. + """ + + roles: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class Options(proto.Message): + r"""Contains query options. + + Attributes: + expand_groups (bool): + Optional. If true, the identities section of the result will + expand any Google groups appearing in an IAM policy binding. + + If + [IamPolicyAnalysisQuery.identity_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.identity_selector] + is specified, the identity in the result will be determined + by the selector, and this flag is not allowed to set. + + If true, the default max expansion per group is 1000 for + AssetService.AnalyzeIamPolicy][]. + + Default is false. + expand_roles (bool): + Optional. If true, the access section of result will expand + any roles appearing in IAM policy bindings to include their + permissions. + + If + [IamPolicyAnalysisQuery.access_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.access_selector] + is specified, the access section of the result will be + determined by the selector, and this flag is not allowed to + set. + + Default is false. + expand_resources (bool): + Optional. If true and + [IamPolicyAnalysisQuery.resource_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.resource_selector] + is not specified, the resource section of the result will + expand any resource attached to an IAM policy to include + resources lower in the resource hierarchy. + + For example, if the request analyzes for which resources + user A has permission P, and the results include an IAM + policy with P on a Google Cloud folder, the results will + also include resources in that folder with permission P. + + If true and + [IamPolicyAnalysisQuery.resource_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.resource_selector] + is specified, the resource section of the result will expand + the specified resource to include resources lower in the + resource hierarchy. Only project or lower resources are + supported. Folder and organization resources cannot be used + together with this option. + + For example, if the request analyzes for which users have + permission P on a Google Cloud project with this option + enabled, the results will include all users who have + permission P on that project or any lower resource. + + If true, the default max expansion per resource is 1000 for + AssetService.AnalyzeIamPolicy][] and 100000 for + AssetService.AnalyzeIamPolicyLongrunning][]. + + Default is false. + output_resource_edges (bool): + Optional. If true, the result will output the + relevant parent/child relationships between + resources. Default is false. + output_group_edges (bool): + Optional. If true, the result will output the + relevant membership relationships between groups + and other groups, and between groups and + principals. Default is false. + analyze_service_account_impersonation (bool): + Optional. If true, the response will include access analysis + from identities to resources via service account + impersonation. This is a very expensive operation, because + many derived queries will be executed. We highly recommend + you use + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning] + RPC instead. + + For example, if the request analyzes for which resources + user A has permission P, and there's an IAM policy states + user A has iam.serviceAccounts.getAccessToken permission to + a service account SA, and there's another IAM policy states + service account SA has permission P to a Google Cloud folder + F, then user A potentially has access to the Google Cloud + folder F. And those advanced analysis results will be + included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Another example, if the request analyzes for who has + permission P to a Google Cloud folder F, and there's an IAM + policy states user A has iam.serviceAccounts.actAs + permission to a service account SA, and there's another IAM + policy states service account SA has permission P to the + Google Cloud folder F, then user A potentially has access to + the Google Cloud folder F. And those advanced analysis + results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Only the following permissions are considered in this + analysis: + + - ``iam.serviceAccounts.actAs`` + - ``iam.serviceAccounts.signBlob`` + - ``iam.serviceAccounts.signJwt`` + - ``iam.serviceAccounts.getAccessToken`` + - ``iam.serviceAccounts.getOpenIdToken`` + - ``iam.serviceAccounts.implicitDelegation`` + + Default is false. + """ + + expand_groups: bool = proto.Field( + proto.BOOL, + number=1, + ) + expand_roles: bool = proto.Field( + proto.BOOL, + number=2, + ) + expand_resources: bool = proto.Field( + proto.BOOL, + number=3, + ) + output_resource_edges: bool = proto.Field( + proto.BOOL, + number=4, + ) + output_group_edges: bool = proto.Field( + proto.BOOL, + number=5, + ) + analyze_service_account_impersonation: bool = proto.Field( + proto.BOOL, + number=6, + ) + + class ConditionContext(proto.Message): + r"""The IAM conditions context. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + access_time (google.protobuf.timestamp_pb2.Timestamp): + The hypothetical access timestamp to evaluate IAM + conditions. Note that this value must not be earlier than + the current time; otherwise, an INVALID_ARGUMENT error will + be returned. + + This field is a member of `oneof`_ ``TimeContext``. + """ + + access_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + oneof='TimeContext', + message=timestamp_pb2.Timestamp, + ) + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + resource_selector: ResourceSelector = proto.Field( + proto.MESSAGE, + number=2, + message=ResourceSelector, + ) + identity_selector: IdentitySelector = proto.Field( + proto.MESSAGE, + number=3, + message=IdentitySelector, + ) + access_selector: AccessSelector = proto.Field( + proto.MESSAGE, + number=4, + message=AccessSelector, + ) + options: Options = proto.Field( + proto.MESSAGE, + number=5, + message=Options, + ) + condition_context: ConditionContext = proto.Field( + proto.MESSAGE, + number=6, + message=ConditionContext, + ) + + +class AnalyzeIamPolicyRequest(proto.Message): + r"""A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + + Attributes: + analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): + Required. The request query. + saved_analysis_query (str): + Optional. The name of a saved query, which must be in the + format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + If both ``analysis_query`` and ``saved_analysis_query`` are + provided, they will be merged together with the + ``saved_analysis_query`` as base and the ``analysis_query`` + as overrides. For more details of the merge behavior, please + refer to the + `MergeFrom `__ + page. + + Note that you cannot override primitive fields with default + value, such as 0 or empty string, etc., because we use + proto3, which doesn't support field presence yet. + execution_timeout (google.protobuf.duration_pb2.Duration): + Optional. Amount of time executable has to complete. See + JSON representation of + `Duration `__. + + If this field is set with a value less than the RPC + deadline, and the execution of your query hasn't finished in + the specified execution timeout, you will get a response + with partial result. Otherwise, your query's execution will + continue until the RPC deadline. If it's not finished until + then, you will get a DEADLINE_EXCEEDED error. + + Default is empty. + """ + + analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + saved_analysis_query: str = proto.Field( + proto.STRING, + number=3, + ) + execution_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class AnalyzeIamPolicyResponse(proto.Message): + r"""A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. + + Attributes: + main_analysis (google.cloud.asset_v1.types.AnalyzeIamPolicyResponse.IamPolicyAnalysis): + The main analysis that matches the original + request. + service_account_impersonation_analysis (MutableSequence[google.cloud.asset_v1.types.AnalyzeIamPolicyResponse.IamPolicyAnalysis]): + The service account impersonation analysis if + [AnalyzeIamPolicyRequest.analyze_service_account_impersonation][] + is enabled. + fully_explored (bool): + Represents whether all entries in the + [main_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.main_analysis] + and + [service_account_impersonation_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis] + have been fully explored to answer the query in the request. + """ + + class IamPolicyAnalysis(proto.Message): + r"""An analysis message to group the query and results. + + Attributes: + analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): + The analysis query. + analysis_results (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult]): + A list of + [IamPolicyAnalysisResult][google.cloud.asset.v1.IamPolicyAnalysisResult] + that matches the analysis query, or empty if no result is + found. + fully_explored (bool): + Represents whether all entries in the + [analysis_results][google.cloud.asset.v1.AnalyzeIamPolicyResponse.IamPolicyAnalysis.analysis_results] + have been fully explored to answer the query. + non_critical_errors (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisState]): + A list of non-critical errors happened during + the query handling. + """ + + analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + analysis_results: MutableSequence[gca_assets.IamPolicyAnalysisResult] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gca_assets.IamPolicyAnalysisResult, + ) + fully_explored: bool = proto.Field( + proto.BOOL, + number=3, + ) + non_critical_errors: MutableSequence[gca_assets.IamPolicyAnalysisState] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gca_assets.IamPolicyAnalysisState, + ) + + main_analysis: IamPolicyAnalysis = proto.Field( + proto.MESSAGE, + number=1, + message=IamPolicyAnalysis, + ) + service_account_impersonation_analysis: MutableSequence[IamPolicyAnalysis] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=IamPolicyAnalysis, + ) + fully_explored: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class IamPolicyAnalysisOutputConfig(proto.Message): + r"""Output configuration for export IAM policy analysis + destination. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.GcsDestination): + Destination on Cloud Storage. + + This field is a member of `oneof`_ ``destination``. + bigquery_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.BigQueryDestination): + Destination on BigQuery. + + This field is a member of `oneof`_ ``destination``. + """ + + class GcsDestination(proto.Message): + r"""A Cloud Storage location. + + Attributes: + uri (str): + Required. The URI of the Cloud Storage object. It's the same + URI that is used by gsutil. Example: + "gs://bucket_name/object_name". See `Viewing and Editing + Object + Metadata `__ + for more information. + + If the specified Cloud Storage object already exists and + there is no + `hold `__, + it will be overwritten with the analysis result. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + class BigQueryDestination(proto.Message): + r"""A BigQuery destination. + + Attributes: + dataset (str): + Required. The BigQuery dataset in format + "projects/projectId/datasets/datasetId", to which the + analysis results should be exported. If this dataset does + not exist, the export call will return an INVALID_ARGUMENT + error. + table_prefix (str): + Required. The prefix of the BigQuery tables to which the + analysis results will be written. Tables will be created + based on this table_prefix if not exist: + + - _analysis table will contain export + operation's metadata. + - _analysis_result will contain all the + [IamPolicyAnalysisResult][google.cloud.asset.v1.IamPolicyAnalysisResult]. + When [partition_key] is specified, both tables will be + partitioned based on the [partition_key]. + partition_key (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey): + The partition key for BigQuery partitioned + table. + write_disposition (str): + Optional. Specifies the action that occurs if the + destination table or partition already exists. The following + values are supported: + + - WRITE_TRUNCATE: If the table or partition already exists, + BigQuery overwrites the entire table or all the + partitions data. + - WRITE_APPEND: If the table or partition already exists, + BigQuery appends the data to the table or the latest + partition. + - WRITE_EMPTY: If the table already exists and contains + data, an error is returned. + + The default value is WRITE_APPEND. Each action is atomic and + only occurs if BigQuery is able to complete the job + successfully. Details are at + https://cloud.google.com/bigquery/docs/loading-data-local#appending_to_or_overwriting_a_table_using_a_local_file. + """ + class PartitionKey(proto.Enum): + r"""This enum determines the partition key column for the + bigquery tables. Partitioning can improve query performance and + reduce query cost by filtering partitions. Refer to + https://cloud.google.com/bigquery/docs/partitioned-tables for + details. + + Values: + PARTITION_KEY_UNSPECIFIED (0): + Unspecified partition key. Tables won't be + partitioned using this option. + REQUEST_TIME (1): + The time when the request is received. If + specified as partition key, the result table(s) + is partitoned by the RequestTime column, an + additional timestamp column representing when + the request was received. + """ + PARTITION_KEY_UNSPECIFIED = 0 + REQUEST_TIME = 1 + + dataset: str = proto.Field( + proto.STRING, + number=1, + ) + table_prefix: str = proto.Field( + proto.STRING, + number=2, + ) + partition_key: 'IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey' = proto.Field( + proto.ENUM, + number=3, + enum='IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey', + ) + write_disposition: str = proto.Field( + proto.STRING, + number=4, + ) + + gcs_destination: GcsDestination = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message=GcsDestination, + ) + bigquery_destination: BigQueryDestination = proto.Field( + proto.MESSAGE, + number=2, + oneof='destination', + message=BigQueryDestination, + ) + + +class AnalyzeIamPolicyLongrunningRequest(proto.Message): + r"""A request message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + + Attributes: + analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): + Required. The request query. + saved_analysis_query (str): + Optional. The name of a saved query, which must be in the + format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + + If both ``analysis_query`` and ``saved_analysis_query`` are + provided, they will be merged together with the + ``saved_analysis_query`` as base and the ``analysis_query`` + as overrides. For more details of the merge behavior, please + refer to the + `MergeFrom `__ + doc. + + Note that you cannot override primitive fields with default + value, such as 0 or empty string, etc., because we use + proto3, which doesn't support field presence yet. + output_config (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig): + Required. Output configuration indicating + where the results will be output to. + """ + + analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + saved_analysis_query: str = proto.Field( + proto.STRING, + number=3, + ) + output_config: 'IamPolicyAnalysisOutputConfig' = proto.Field( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisOutputConfig', + ) + + +class AnalyzeIamPolicyLongrunningResponse(proto.Message): + r"""A response message for + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. + + """ + + +class SavedQuery(proto.Message): + r"""A saved query which can be shared with others or used later. + + Attributes: + name (str): + The resource name of the saved query. The format must be: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + description (str): + The description of this saved query. This + value should be fewer than 255 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create time of this saved + query. + creator (str): + Output only. The account's email address who + has created this saved query. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last update time of this + saved query. + last_updater (str): + Output only. The account's email address who + has updated this saved query most recently. + labels (MutableMapping[str, str]): + Labels applied on the resource. + This value should not contain more than 10 + entries. The key and value of each entry must be + non-empty and fewer than 64 characters. + content (google.cloud.asset_v1.types.SavedQuery.QueryContent): + The query content. + """ + + class QueryContent(proto.Message): + r"""The query content. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + iam_policy_analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): + An IAM Policy Analysis query, which could be used in the + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy] + RPC or the + [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning] + RPC. + + This field is a member of `oneof`_ ``query_content``. + """ + + iam_policy_analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( + proto.MESSAGE, + number=1, + oneof='query_content', + message='IamPolicyAnalysisQuery', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + creator: str = proto.Field( + proto.STRING, + number=4, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + last_updater: str = proto.Field( + proto.STRING, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + content: QueryContent = proto.Field( + proto.MESSAGE, + number=8, + message=QueryContent, + ) + + +class CreateSavedQueryRequest(proto.Message): + r"""Request to create a saved query. + + Attributes: + parent (str): + Required. The name of the project/folder/organization where + this saved_query should be created in. It can only be an + organization number (such as "organizations/123"), a folder + number (such as "folders/123"), a project ID (such as + "projects/my-project-id"), or a project number (such as + "projects/12345"). + saved_query (google.cloud.asset_v1.types.SavedQuery): + Required. The saved_query details. The ``name`` field must + be empty as it will be generated based on the parent and + saved_query_id. + saved_query_id (str): + Required. The ID to use for the saved query, which must be + unique in the specified parent. It will become the final + component of the saved query's resource name. + + This value should be 4-63 characters, and valid characters + are ``[a-z][0-9]-``. + + Notice that this field is required in the saved query + creation, and the ``name`` field of the ``saved_query`` will + be ignored. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + saved_query: 'SavedQuery' = proto.Field( + proto.MESSAGE, + number=2, + message='SavedQuery', + ) + saved_query_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetSavedQueryRequest(proto.Message): + r"""Request to get a saved query. + + Attributes: + name (str): + Required. The name of the saved query and it must be in the + format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSavedQueriesRequest(proto.Message): + r"""Request to list saved queries. + + Attributes: + parent (str): + Required. The parent + project/folder/organization whose savedQueries + are to be listed. It can only be using + project/folder/organization number (such as + "folders/12345")", or a project ID (such as + "projects/my-project-id"). + filter (str): + Optional. The expression to filter resources. The expression + is a list of zero or more restrictions combined via logical + operators ``AND`` and ``OR``. When ``AND`` and ``OR`` are + both used in the expression, parentheses must be + appropriately used to group the combinations. The expression + may also contain regular expressions. + + See https://google.aip.dev/160 for more information on the + grammar. + page_size (int): + Optional. The maximum number of saved queries + to return per page. The service may return fewer + than this value. If unspecified, at most 50 will + be returned. The maximum value is 1000; values + above 1000 will be coerced to 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListSavedQueries`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListSavedQueries`` must match the call that provided the + page token. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSavedQueriesResponse(proto.Message): + r"""Response of listing saved queries. + + Attributes: + saved_queries (MutableSequence[google.cloud.asset_v1.types.SavedQuery]): + A list of savedQueries. + 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 + + saved_queries: MutableSequence['SavedQuery'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='SavedQuery', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateSavedQueryRequest(proto.Message): + r"""Request to update a saved query. + + Attributes: + saved_query (google.cloud.asset_v1.types.SavedQuery): + Required. The saved query to update. + + The saved query's ``name`` field is used to identify the one + to update, which has format as below: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. The list of fields to update. + """ + + saved_query: 'SavedQuery' = proto.Field( + proto.MESSAGE, + number=1, + message='SavedQuery', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteSavedQueryRequest(proto.Message): + r"""Request to delete a saved query. + + Attributes: + name (str): + Required. The name of the saved query to delete. It must be + in the format of: + + - projects/project_number/savedQueries/saved_query_id + - folders/folder_number/savedQueries/saved_query_id + - organizations/organization_number/savedQueries/saved_query_id + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AnalyzeMoveRequest(proto.Message): + r"""The request message for performing resource move analysis. + + Attributes: + resource (str): + Required. Name of the resource to perform the + analysis against. Only Google Cloud projects are + supported as of today. Hence, this can only be a + project ID (such as "projects/my-project-id") or + a project number (such as "projects/12345"). + destination_parent (str): + Required. Name of the Google Cloud folder or + organization to reparent the target resource. + The analysis will be performed against + hypothetically moving the resource to this + specified desitination parent. This can only be + a folder number (such as "folders/123") or an + organization number (such as + "organizations/123"). + view (google.cloud.asset_v1.types.AnalyzeMoveRequest.AnalysisView): + Analysis view indicating what information + should be included in the analysis response. If + unspecified, the default view is FULL. + """ + class AnalysisView(proto.Enum): + r"""View enum for supporting partial analysis responses. + + Values: + ANALYSIS_VIEW_UNSPECIFIED (0): + The default/unset value. + The API will default to the FULL view. + FULL (1): + Full analysis including all level of impacts + of the specified resource move. + BASIC (2): + Basic analysis only including blockers which + will prevent the specified resource move at + runtime. + """ + ANALYSIS_VIEW_UNSPECIFIED = 0 + FULL = 1 + BASIC = 2 + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + destination_parent: str = proto.Field( + proto.STRING, + number=2, + ) + view: AnalysisView = proto.Field( + proto.ENUM, + number=3, + enum=AnalysisView, + ) + + +class AnalyzeMoveResponse(proto.Message): + r"""The response message for resource move analysis. + + Attributes: + move_analysis (MutableSequence[google.cloud.asset_v1.types.MoveAnalysis]): + The list of analyses returned from performing + the intended resource move analysis. The + analysis is grouped by different Google Cloud + services. + """ + + move_analysis: MutableSequence['MoveAnalysis'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MoveAnalysis', + ) + + +class MoveAnalysis(proto.Message): + r"""A message to group the analysis information. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + The user friendly display name of the + analysis. E.g. IAM, organization policy etc. + analysis (google.cloud.asset_v1.types.MoveAnalysisResult): + Analysis result of moving the target + resource. + + This field is a member of `oneof`_ ``result``. + error (google.rpc.status_pb2.Status): + Description of error encountered when + performing the analysis. + + This field is a member of `oneof`_ ``result``. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + analysis: 'MoveAnalysisResult' = proto.Field( + proto.MESSAGE, + number=2, + oneof='result', + message='MoveAnalysisResult', + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + oneof='result', + message=status_pb2.Status, + ) + + +class MoveAnalysisResult(proto.Message): + r"""An analysis result including blockers and warnings. + + Attributes: + blockers (MutableSequence[google.cloud.asset_v1.types.MoveImpact]): + Blocking information that would prevent the + target resource from moving to the specified + destination at runtime. + warnings (MutableSequence[google.cloud.asset_v1.types.MoveImpact]): + Warning information indicating that moving + the target resource to the specified destination + might be unsafe. This can include important + policy information and configuration changes, + but will not block moves at runtime. + """ + + blockers: MutableSequence['MoveImpact'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='MoveImpact', + ) + warnings: MutableSequence['MoveImpact'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='MoveImpact', + ) + + +class MoveImpact(proto.Message): + r"""A message to group impacts of moving the target resource. + + Attributes: + detail (str): + User friendly impact detail in a free form + message. + """ + + detail: str = proto.Field( + proto.STRING, + number=1, + ) + + +class QueryAssetsOutputConfig(proto.Message): + r"""Output configuration query assets. + + Attributes: + bigquery_destination (google.cloud.asset_v1.types.QueryAssetsOutputConfig.BigQueryDestination): + BigQuery destination where the query results + will be saved. + """ + + class BigQueryDestination(proto.Message): + r"""BigQuery destination. + + Attributes: + dataset (str): + Required. The BigQuery dataset where the + query results will be saved. It has the format + of "projects/{projectId}/datasets/{datasetId}". + table (str): + Required. The BigQuery table where the query + results will be saved. If this table does not + exist, a new table with the given name will be + created. + write_disposition (str): + Specifies the action that occurs if the destination table or + partition already exists. The following values are + supported: + + - WRITE_TRUNCATE: If the table or partition already exists, + BigQuery overwrites the entire table or all the + partitions data. + - WRITE_APPEND: If the table or partition already exists, + BigQuery appends the data to the table or the latest + partition. + - WRITE_EMPTY: If the table already exists and contains + data, a 'duplicate' error is returned in the job result. + + The default value is WRITE_EMPTY. + """ + + dataset: str = proto.Field( + proto.STRING, + number=1, + ) + table: str = proto.Field( + proto.STRING, + number=2, + ) + write_disposition: str = proto.Field( + proto.STRING, + number=3, + ) + + bigquery_destination: BigQueryDestination = proto.Field( + proto.MESSAGE, + number=1, + message=BigQueryDestination, + ) + + +class QueryAssetsRequest(proto.Message): + r"""QueryAssets request. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The relative name of the root asset. This can only + be an organization number (such as "organizations/123"), a + project ID (such as "projects/my-project-id"), or a project + number (such as "projects/12345"), or a folder number (such + as "folders/123"). + + Only assets belonging to the ``parent`` will be returned. + statement (str): + Optional. A SQL statement that's compatible with `BigQuery + SQL `__. + + This field is a member of `oneof`_ ``query``. + job_reference (str): + Optional. Reference to the query job, which is from the + ``QueryAssetsResponse`` of previous ``QueryAssets`` call. + + This field is a member of `oneof`_ ``query``. + page_size (int): + Optional. The maximum number of rows to return in the + results. Responses are limited to 10 MB and 1000 rows. + + By default, the maximum row count is 1000. When the byte or + row count limit is reached, the rest of the query results + will be paginated. + + The field will be ignored when [output_config] is specified. + page_token (str): + Optional. A page token received from previous + ``QueryAssets``. + + The field will be ignored when [output_config] is specified. + timeout (google.protobuf.duration_pb2.Duration): + Optional. Specifies the maximum amount of time that the + client is willing to wait for the query to complete. By + default, this limit is 5 min for the first query, and 1 + minute for the following queries. If the query is complete, + the ``done`` field in the ``QueryAssetsResponse`` is true, + otherwise false. + + Like BigQuery `jobs.query + API `__ + The call is not guaranteed to wait for the specified + timeout; it typically returns after around 200 seconds + (200,000 milliseconds), even if the query is not complete. + + The field will be ignored when [output_config] is specified. + read_time_window (google.cloud.asset_v1.types.TimeWindow): + Optional. [start_time] is required. [start_time] must be + less than [end_time] Defaults [end_time] to now if + [start_time] is set and [end_time] isn't. Maximum permitted + time range is 7 days. + + This field is a member of `oneof`_ ``time``. + read_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Queries cloud assets as they + appeared at the specified point in time. + + This field is a member of `oneof`_ ``time``. + output_config (google.cloud.asset_v1.types.QueryAssetsOutputConfig): + Optional. Destination where the query results will be saved. + + When this field is specified, the query results won't be + saved in the [QueryAssetsResponse.query_result]. Instead + [QueryAssetsResponse.output_config] will be set. + + Meanwhile, [QueryAssetsResponse.job_reference] will be set + and can be used to check the status of the query job when + passed to a following [QueryAssets] API call. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + statement: str = proto.Field( + proto.STRING, + number=2, + oneof='query', + ) + job_reference: str = proto.Field( + proto.STRING, + number=3, + oneof='query', + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + read_time_window: gca_assets.TimeWindow = proto.Field( + proto.MESSAGE, + number=7, + oneof='time', + message=gca_assets.TimeWindow, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + oneof='time', + message=timestamp_pb2.Timestamp, + ) + output_config: 'QueryAssetsOutputConfig' = proto.Field( + proto.MESSAGE, + number=9, + message='QueryAssetsOutputConfig', + ) + + +class QueryAssetsResponse(proto.Message): + r"""QueryAssets response. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + job_reference (str): + Reference to a query job. + done (bool): + The query response, which can be either an ``error`` or a + valid ``response``. + + If ``done`` == ``false`` and the query result is being saved + in a output, the output_config field will be set. If + ``done`` == ``true``, exactly one of ``error``, + ``query_result`` or ``output_config`` will be set. + error (google.rpc.status_pb2.Status): + Error status. + + This field is a member of `oneof`_ ``response``. + query_result (google.cloud.asset_v1.types.QueryResult): + Result of the query. + + This field is a member of `oneof`_ ``response``. + output_config (google.cloud.asset_v1.types.QueryAssetsOutputConfig): + Output configuration which indicates instead + of being returned in API response on the fly, + the query result will be saved in a specific + output. + + This field is a member of `oneof`_ ``response``. + """ + + job_reference: str = proto.Field( + proto.STRING, + number=1, + ) + done: bool = proto.Field( + proto.BOOL, + number=2, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + oneof='response', + message=status_pb2.Status, + ) + query_result: 'QueryResult' = proto.Field( + proto.MESSAGE, + number=4, + oneof='response', + message='QueryResult', + ) + output_config: 'QueryAssetsOutputConfig' = proto.Field( + proto.MESSAGE, + number=5, + oneof='response', + message='QueryAssetsOutputConfig', + ) + + +class QueryResult(proto.Message): + r"""Execution results of the query. + + The result is formatted as rows represented by BigQuery compatible + [schema]. When pagination is necessary, it will contains the page + token to retrieve the results of following pages. + + Attributes: + rows (MutableSequence[google.protobuf.struct_pb2.Struct]): + Each row hold a query result in the format of ``Struct``. + schema (google.cloud.asset_v1.types.TableSchema): + Describes the format of the [rows]. + next_page_token (str): + Token to retrieve the next page of the + results. + total_rows (int): + Total rows of the whole query results. + """ + + @property + def raw_page(self): + return self + + rows: MutableSequence[struct_pb2.Struct] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + schema: 'TableSchema' = proto.Field( + proto.MESSAGE, + number=2, + message='TableSchema', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + total_rows: int = proto.Field( + proto.INT64, + number=4, + ) + + +class TableSchema(proto.Message): + r"""BigQuery Compatible table schema. + + Attributes: + fields (MutableSequence[google.cloud.asset_v1.types.TableFieldSchema]): + Describes the fields in a table. + """ + + fields: MutableSequence['TableFieldSchema'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='TableFieldSchema', + ) + + +class TableFieldSchema(proto.Message): + r"""A field in TableSchema. + + Attributes: + field (str): + The field name. The name must contain only letters (a-z, + A-Z), numbers (0-9), or underscores (_), and must start with + a letter or underscore. The maximum length is 128 + characters. + type_ (str): + The field data type. Possible values include + + - STRING + - BYTES + - INTEGER + - FLOAT + - BOOLEAN + - TIMESTAMP + - DATE + - TIME + - DATETIME + - GEOGRAPHY, + - NUMERIC, + - BIGNUMERIC, + - RECORD (where RECORD indicates that the field contains a + nested schema). + mode (str): + The field mode. Possible values include + NULLABLE, REQUIRED and REPEATED. The default + value is NULLABLE. + fields (MutableSequence[google.cloud.asset_v1.types.TableFieldSchema]): + Describes the nested schema fields if the + type property is set to RECORD. + """ + + field: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + mode: str = proto.Field( + proto.STRING, + number=3, + ) + fields: MutableSequence['TableFieldSchema'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='TableFieldSchema', + ) + + +class BatchGetEffectiveIamPoliciesRequest(proto.Message): + r"""A request message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + + Attributes: + scope (str): + Required. Only IAM policies on or below the scope will be + returned. + + This can only be an organization number (such as + "organizations/123"), a folder number (such as + "folders/123"), a project ID (such as + "projects/my-project-id"), or a project number (such as + "projects/12345"). + + To know how to get organization id, visit + `here `__. + + To know how to get folder or project id, visit + `here `__. + names (MutableSequence[str]): + Required. The names refer to the [full_resource_names] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of `searchable asset + types `__. + A maximum of 20 resources' effective policies can be + retrieved in a batch. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class BatchGetEffectiveIamPoliciesResponse(proto.Message): + r"""A response message for + [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. + + Attributes: + policy_results (MutableSequence[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy]): + The effective policies for a batch of resources. Note that + the results order is the same as the order of + [BatchGetEffectiveIamPoliciesRequest.names][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesRequest.names]. + When a resource does not have any effective IAM policies, + its corresponding policy_result will contain empty + [EffectiveIamPolicy.policies][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.policies]. + """ + + class EffectiveIamPolicy(proto.Message): + r"""The effective IAM policies on one resource. + + Attributes: + full_resource_name (str): + The [full_resource_name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + for which the + [policies][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.policies] + are computed. This is one of the + [BatchGetEffectiveIamPoliciesRequest.names][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesRequest.names] + the caller provides in the request. + policies (MutableSequence[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo]): + The effective policies for the + [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name]. + + These policies include the policy set on the + [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name] + and those set on its parents and ancestors up to the + [BatchGetEffectiveIamPoliciesRequest.scope][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesRequest.scope]. + Note that these policies are not filtered according to the + resource type of the + [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name]. + + These policies are hierarchically ordered by + [PolicyInfo.attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource] + starting from + [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name] + itself to its parents and ancestors, such that policies[i]'s + [PolicyInfo.attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource] + is the child of policies[i+1]'s + [PolicyInfo.attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource], + if policies[i+1] exists. + """ + + class PolicyInfo(proto.Message): + r"""The IAM policy and its attached resource. + + Attributes: + attached_resource (str): + The full resource name the + [policy][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.policy] + is directly attached to. + policy (google.iam.v1.policy_pb2.Policy): + The IAM policy that's directly attached to the + [attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource]. + """ + + attached_resource: str = proto.Field( + proto.STRING, + number=1, + ) + policy: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=2, + message=policy_pb2.Policy, + ) + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + policies: MutableSequence['BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo', + ) + + policy_results: MutableSequence[EffectiveIamPolicy] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=EffectiveIamPolicy, + ) + + +class AnalyzerOrgPolicy(proto.Message): + r"""This organization policy message is a modified version of the + one defined in the Organization Policy system. This message + contains several fields defined in the original organization + policy with some new fields for analysis purpose. + + Attributes: + attached_resource (str): + The [full resource name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of an organization/folder/project resource where this + organization policy is set. + + Notice that some type of constraints are defined with + default policy. This field will be empty for them. + applied_resource (str): + The [full resource name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of an organization/folder/project resource where this + organization policy applies to. + + For any user defined org policies, this field has the same + value as the [attached_resource] field. Only for default + policy, this field has the different value. + rules (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy.Rule]): + List of rules for this organization policy. + inherit_from_parent (bool): + If ``inherit_from_parent`` is true, Rules set higher up in + the hierarchy (up to the closest root) are inherited and + present in the effective policy. If it is false, then no + rules are inherited, and this policy becomes the effective + root for evaluation. + reset (bool): + Ignores policies set above this resource and restores the + default behavior of the constraint at this resource. This + field can be set in policies for either list or boolean + constraints. If set, ``rules`` must be empty and + ``inherit_from_parent`` must be set to false. + """ + + class Rule(proto.Message): + r"""This rule message is a customized version of the one defined + in the Organization Policy system. In addition to the fields + defined in the original organization policy, it contains + additional field(s) under specific circumstances to support + analysis results. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + values (google.cloud.asset_v1.types.AnalyzerOrgPolicy.Rule.StringValues): + List of values to be used for this + PolicyRule. This field can be set only in + Policies for list constraints. + + This field is a member of `oneof`_ ``kind``. + allow_all (bool): + Setting this to true means that all values + are allowed. This field can be set only in + Policies for list constraints. + + This field is a member of `oneof`_ ``kind``. + deny_all (bool): + Setting this to true means that all values + are denied. This field can be set only in + Policies for list constraints. + + This field is a member of `oneof`_ ``kind``. + enforce (bool): + If ``true``, then the ``Policy`` is enforced. If ``false``, + then any configuration is acceptable. This field can be set + only in Policies for boolean constraints. + + This field is a member of `oneof`_ ``kind``. + condition (google.type.expr_pb2.Expr): + The evaluating condition for this rule. + """ + + class StringValues(proto.Message): + r"""The string values for the list constraints. + + Attributes: + allowed_values (MutableSequence[str]): + List of values allowed at this resource. + denied_values (MutableSequence[str]): + List of values denied at this resource. + """ + + allowed_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + denied_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + values: 'AnalyzerOrgPolicy.Rule.StringValues' = proto.Field( + proto.MESSAGE, + number=3, + oneof='kind', + message='AnalyzerOrgPolicy.Rule.StringValues', + ) + allow_all: bool = proto.Field( + proto.BOOL, + number=4, + oneof='kind', + ) + deny_all: bool = proto.Field( + proto.BOOL, + number=5, + oneof='kind', + ) + enforce: bool = proto.Field( + proto.BOOL, + number=6, + oneof='kind', + ) + condition: expr_pb2.Expr = proto.Field( + proto.MESSAGE, + number=7, + message=expr_pb2.Expr, + ) + + attached_resource: str = proto.Field( + proto.STRING, + number=1, + ) + applied_resource: str = proto.Field( + proto.STRING, + number=5, + ) + rules: MutableSequence[Rule] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Rule, + ) + inherit_from_parent: bool = proto.Field( + proto.BOOL, + number=3, + ) + reset: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class AnalyzerOrgPolicyConstraint(proto.Message): + r"""The organization policy constraint definition. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + google_defined_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint): + The definition of the canned constraint + defined by Google. + + This field is a member of `oneof`_ ``constraint_definition``. + custom_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.CustomConstraint): + The definition of the custom constraint. + + This field is a member of `oneof`_ ``constraint_definition``. + """ + + class Constraint(proto.Message): + r"""The definition of a constraint. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The unique name of the constraint. Format of the name should + be + + - ``constraints/{constraint_name}`` + + For example, + ``constraints/compute.disableSerialPortAccess``. + display_name (str): + The human readable name of the constraint. + description (str): + Detailed description of what this ``Constraint`` controls as + well as how and where it is enforced. + constraint_default (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint.ConstraintDefault): + The evaluation behavior of this constraint in + the absence of 'Policy'. + list_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint.ListConstraint): + Defines this constraint as being a + ListConstraint. + + This field is a member of `oneof`_ ``constraint_type``. + boolean_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint.BooleanConstraint): + Defines this constraint as being a + BooleanConstraint. + + This field is a member of `oneof`_ ``constraint_type``. + """ + class ConstraintDefault(proto.Enum): + r"""Specifies the default behavior in the absence of any ``Policy`` for + the ``Constraint``. This must not be + ``CONSTRAINT_DEFAULT_UNSPECIFIED``. + + Values: + CONSTRAINT_DEFAULT_UNSPECIFIED (0): + This is only used for distinguishing unset + values and should never be used. + ALLOW (1): + Indicate that all values are allowed for list + constraints. Indicate that enforcement is off + for boolean constraints. + DENY (2): + Indicate that all values are denied for list + constraints. Indicate that enforcement is on for + boolean constraints. + """ + CONSTRAINT_DEFAULT_UNSPECIFIED = 0 + ALLOW = 1 + DENY = 2 + + class ListConstraint(proto.Message): + r"""A ``Constraint`` that allows or disallows a list of string values, + which are configured by an organization's policy administrator with + a ``Policy``. + + Attributes: + supports_in (bool): + Indicates whether values grouped into categories can be used + in ``Policy.allowed_values`` and ``Policy.denied_values``. + For example, ``"in:Python"`` would match any value in the + 'Python' group. + supports_under (bool): + Indicates whether subtrees of Cloud Resource Manager + resource hierarchy can be used in ``Policy.allowed_values`` + and ``Policy.denied_values``. For example, + ``"under:folders/123"`` would match any resource under the + 'folders/123' folder. + """ + + supports_in: bool = proto.Field( + proto.BOOL, + number=1, + ) + supports_under: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class BooleanConstraint(proto.Message): + r"""A ``Constraint`` that is either enforced or not. + + For example a constraint + ``constraints/compute.disableSerialPortAccess``. If it is enforced + on a VM instance, serial port connections will not be opened to that + instance. + + """ + + 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, + ) + constraint_default: 'AnalyzerOrgPolicyConstraint.Constraint.ConstraintDefault' = proto.Field( + proto.ENUM, + number=4, + enum='AnalyzerOrgPolicyConstraint.Constraint.ConstraintDefault', + ) + list_constraint: 'AnalyzerOrgPolicyConstraint.Constraint.ListConstraint' = proto.Field( + proto.MESSAGE, + number=5, + oneof='constraint_type', + message='AnalyzerOrgPolicyConstraint.Constraint.ListConstraint', + ) + boolean_constraint: 'AnalyzerOrgPolicyConstraint.Constraint.BooleanConstraint' = proto.Field( + proto.MESSAGE, + number=6, + oneof='constraint_type', + message='AnalyzerOrgPolicyConstraint.Constraint.BooleanConstraint', + ) + + class CustomConstraint(proto.Message): + r"""The definition of a custom constraint. + + Attributes: + name (str): + Name of the constraint. This is unique within the + organization. Format of the name should be + + - ``organizations/{organization_id}/customConstraints/{custom_constraint_id}`` + + Example : + "organizations/123/customConstraints/custom.createOnlyE2TypeVms". + resource_types (MutableSequence[str]): + The Resource Instance type on which this policy applies to. + Format will be of the form : "/" Example: + + - ``compute.googleapis.com/Instance``. + method_types (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.CustomConstraint.MethodType]): + All the operations being applied for this + constraint. + condition (str): + Organization Policy condition/expression. For example: + ``resource.instanceName.matches("[production|test]_.*_(\d)+")'`` + or, ``resource.management.auto_upgrade == true`` + action_type (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.CustomConstraint.ActionType): + Allow or deny type. + display_name (str): + One line display name for the UI. + description (str): + Detailed information about this custom policy + constraint. + """ + class MethodType(proto.Enum): + r"""The operation in which this constraint will be applied. For example: + If the constraint applies only when create VMs, the method_types + will be "CREATE" only. If the constraint applied when create or + delete VMs, the method_types will be "CREATE" and "DELETE". + + Values: + METHOD_TYPE_UNSPECIFIED (0): + Unspecified. Will results in user error. + CREATE (1): + Constraint applied when creating the + resource. + UPDATE (2): + Constraint applied when updating the + resource. + DELETE (3): + Constraint applied when deleting the + resource. + """ + METHOD_TYPE_UNSPECIFIED = 0 + CREATE = 1 + UPDATE = 2 + DELETE = 3 + + class ActionType(proto.Enum): + r"""Allow or deny type. + + Values: + ACTION_TYPE_UNSPECIFIED (0): + Unspecified. Will results in user error. + ALLOW (1): + Allowed action type. + DENY (2): + Deny action type. + """ + ACTION_TYPE_UNSPECIFIED = 0 + ALLOW = 1 + DENY = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + method_types: MutableSequence['AnalyzerOrgPolicyConstraint.CustomConstraint.MethodType'] = proto.RepeatedField( + proto.ENUM, + number=3, + enum='AnalyzerOrgPolicyConstraint.CustomConstraint.MethodType', + ) + condition: str = proto.Field( + proto.STRING, + number=4, + ) + action_type: 'AnalyzerOrgPolicyConstraint.CustomConstraint.ActionType' = proto.Field( + proto.ENUM, + number=5, + enum='AnalyzerOrgPolicyConstraint.CustomConstraint.ActionType', + ) + display_name: str = proto.Field( + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + + google_defined_constraint: Constraint = proto.Field( + proto.MESSAGE, + number=1, + oneof='constraint_definition', + message=Constraint, + ) + custom_constraint: CustomConstraint = proto.Field( + proto.MESSAGE, + number=2, + oneof='constraint_definition', + message=CustomConstraint, + ) + + +class AnalyzeOrgPoliciesRequest(proto.Message): + r"""A request message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scope (str): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + constraint (str): + Required. The name of the constraint to + analyze organization policies for. The response + only contains analyzed organization policies for + the provided constraint. + filter (str): + The expression to filter + [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. + The only supported field is + ``consolidated_policy.attached_resource``, and the only + supported operator is ``=``. + + Example: + consolidated_policy.attached_resource="//cloudresourcemanager.googleapis.com/folders/001" + will return the org policy results of"folders/001". + page_size (int): + The maximum number of items to return per page. If + unspecified, + [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results] + will contain 20 items with a maximum of 200. + + This field is a member of `oneof`_ ``_page_size``. + page_token (str): + The pagination token to retrieve the next + page. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + constraint: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class AnalyzeOrgPoliciesResponse(proto.Message): + r"""The response message for + [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. + + Attributes: + org_policy_results (MutableSequence[google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse.OrgPolicyResult]): + The organization policies under the + [AnalyzeOrgPoliciesRequest.scope][google.cloud.asset.v1.AnalyzeOrgPoliciesRequest.scope] + with the + [AnalyzeOrgPoliciesRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPoliciesRequest.constraint]. + constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint): + The definition of the constraint in the + request. + next_page_token (str): + The page token to fetch the next page for + [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. + """ + + class OrgPolicyResult(proto.Message): + r"""The organization policy result to the query. + + Attributes: + consolidated_policy (google.cloud.asset_v1.types.AnalyzerOrgPolicy): + The consolidated organization policy for the analyzed + resource. The consolidated organization policy is computed + by merging and evaluating + [AnalyzeOrgPoliciesResponse.policy_bundle][]. The evaluation + will respect the organization policy `hierarchy + rules `__. + policy_bundle (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy]): + The ordered list of all organization policies from the + [AnalyzeOrgPoliciesResponse.OrgPolicyResult.consolidated_policy.attached_resource][]. + to the scope specified in the request. + + If the constraint is defined with default policy, it will + also appear in the list. + """ + + consolidated_policy: 'AnalyzerOrgPolicy' = proto.Field( + proto.MESSAGE, + number=1, + message='AnalyzerOrgPolicy', + ) + policy_bundle: MutableSequence['AnalyzerOrgPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='AnalyzerOrgPolicy', + ) + + @property + def raw_page(self): + return self + + org_policy_results: MutableSequence[OrgPolicyResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=OrgPolicyResult, + ) + constraint: 'AnalyzerOrgPolicyConstraint' = proto.Field( + proto.MESSAGE, + number=2, + message='AnalyzerOrgPolicyConstraint', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AnalyzeOrgPolicyGovernedContainersRequest(proto.Message): + r"""A request message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scope (str): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. The + output containers will also be limited to the ones governed + by those in-scope organization policies. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + constraint (str): + Required. The name of the constraint to + analyze governed containers for. The analysis + only contains organization policies for the + provided constraint. + filter (str): + The expression to filter the governed containers in result. + The only supported field is ``parent``, and the only + supported operator is ``=``. + + Example: + parent="//cloudresourcemanager.googleapis.com/folders/001" + will return all containers under "folders/001". + page_size (int): + The maximum number of items to return per page. If + unspecified, + [AnalyzeOrgPolicyGovernedContainersResponse.governed_containers][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.governed_containers] + will contain 100 items with a maximum of 200. + + This field is a member of `oneof`_ ``_page_size``. + page_token (str): + The pagination token to retrieve the next + page. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + constraint: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class AnalyzeOrgPolicyGovernedContainersResponse(proto.Message): + r"""The response message for + [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. + + Attributes: + governed_containers (MutableSequence[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer]): + The list of the analyzed governed containers. + constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint): + The definition of the constraint in the + request. + next_page_token (str): + The page token to fetch the next page for + [AnalyzeOrgPolicyGovernedContainersResponse.governed_containers][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.governed_containers]. + """ + + class GovernedContainer(proto.Message): + r"""The organization/folder/project resource governed by organization + policies of + [AnalyzeOrgPolicyGovernedContainersRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersRequest.constraint]. + + Attributes: + full_resource_name (str): + The [full resource name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of an organization/folder/project resource. + parent (str): + The [full resource name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of the parent of + [AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.full_resource_name][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.full_resource_name]. + consolidated_policy (google.cloud.asset_v1.types.AnalyzerOrgPolicy): + The consolidated organization policy for the analyzed + resource. The consolidated organization policy is computed + by merging and evaluating + [AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.policy_bundle][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.policy_bundle]. + The evaluation will respect the organization policy + `hierarchy + rules `__. + policy_bundle (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy]): + The ordered list of all organization policies from the + [AnalyzeOrgPoliciesResponse.OrgPolicyResult.consolidated_policy.attached_resource][]. + to the scope specified in the request. + + If the constraint is defined with default policy, it will + also appear in the list. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + consolidated_policy: 'AnalyzerOrgPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='AnalyzerOrgPolicy', + ) + policy_bundle: MutableSequence['AnalyzerOrgPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AnalyzerOrgPolicy', + ) + + @property + def raw_page(self): + return self + + governed_containers: MutableSequence[GovernedContainer] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=GovernedContainer, + ) + constraint: 'AnalyzerOrgPolicyConstraint' = proto.Field( + proto.MESSAGE, + number=2, + message='AnalyzerOrgPolicyConstraint', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AnalyzeOrgPolicyGovernedAssetsRequest(proto.Message): + r"""A request message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + scope (str): + Required. The organization to scope the request. Only + organization policies within the scope will be analyzed. The + output assets will also be limited to the ones governed by + those in-scope organization policies. + + - organizations/{ORGANIZATION_NUMBER} (e.g., + "organizations/123456") + constraint (str): + Required. The name of the constraint to + analyze governed assets for. The analysis only + contains analyzed organization policies for the + provided constraint. + filter (str): + The expression to filter the governed assets in result. The + only supported fields for governed resources are + ``governed_resource.project`` and + ``governed_resource.folders``. The only supported fields for + governed iam policies are ``governed_iam_policy.project`` + and ``governed_iam_policy.folders``. The only supported + operator is ``=``. + + Example 1: governed_resource.project="projects/12345678" + filter will return all governed resources under + projects/12345678 including the project ifself, if + applicable. + + Example 2: governed_iam_policy.folders="folders/12345678" + filter will return all governed iam policies under + folders/12345678, if applicable. + page_size (int): + The maximum number of items to return per page. If + unspecified, + [AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets] + will contain 100 items with a maximum of 200. + + This field is a member of `oneof`_ ``_page_size``. + page_token (str): + The pagination token to retrieve the next + page. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + constraint: str = proto.Field( + proto.STRING, + number=2, + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class AnalyzeOrgPolicyGovernedAssetsResponse(proto.Message): + r"""The response message for + [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. + + Attributes: + governed_assets (MutableSequence[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset]): + The list of the analyzed governed assets. + constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint): + The definition of the constraint in the + request. + next_page_token (str): + The page token to fetch the next page for + [AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets]. + """ + + class GovernedResource(proto.Message): + r"""The Google Cloud resources governed by the organization policies of + the + [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. + + Attributes: + full_resource_name (str): + The [full resource name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of the Google Cloud resource. + parent (str): + The [full resource name] + (https://cloud.google.com/asset-inventory/docs/resource-name-format) + of the parent of + [AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource.full_resource_name][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource.full_resource_name]. + project (str): + The project that this resource belongs to, in the format of + projects/{PROJECT_NUMBER}. This field is available when the + resource belongs to a project. + folders (MutableSequence[str]): + The folder(s) that this resource belongs to, in the format + of folders/{FOLDER_NUMBER}. This field is available when the + resource belongs (directly or cascadingly) to one or more + folders. + organization (str): + The organization that this resource belongs to, in the + format of organizations/{ORGANIZATION_NUMBER}. This field is + available when the resource belongs (directly or + cascadingly) to an organization. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + parent: str = proto.Field( + proto.STRING, + number=2, + ) + project: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + organization: str = proto.Field( + proto.STRING, + number=7, + ) + + class GovernedIamPolicy(proto.Message): + r"""The IAM policies governed by the organization policies of the + [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. + + Attributes: + attached_resource (str): + The full resource name of the resource on which this IAM + policy is set. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Cloud Asset Inventory Resource Name + Format `__ + for more information. + policy (google.iam.v1.policy_pb2.Policy): + The IAM policy directly set on the given + resource. + project (str): + The project that this IAM policy belongs to, in the format + of projects/{PROJECT_NUMBER}. This field is available when + the IAM policy belongs to a project. + folders (MutableSequence[str]): + The folder(s) that this IAM policy belongs to, in the format + of folders/{FOLDER_NUMBER}. This field is available when the + IAM policy belongs (directly or cascadingly) to one or more + folders. + organization (str): + The organization that this IAM policy belongs to, in the + format of organizations/{ORGANIZATION_NUMBER}. This field is + available when the IAM policy belongs (directly or + cascadingly) to an organization. + """ + + attached_resource: str = proto.Field( + proto.STRING, + number=1, + ) + policy: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=2, + message=policy_pb2.Policy, + ) + project: str = proto.Field( + proto.STRING, + number=5, + ) + folders: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + organization: str = proto.Field( + proto.STRING, + number=7, + ) + + class GovernedAsset(proto.Message): + r"""Represents a Google Cloud asset(resource or IAM policy) governed by + the organization policies of the + [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + governed_resource (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource): + A Google Cloud resource governed by the organization + policies of the + [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. + + This field is a member of `oneof`_ ``governed_asset``. + governed_iam_policy (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedIamPolicy): + An IAM policy governed by the organization policies of the + [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. + + This field is a member of `oneof`_ ``governed_asset``. + consolidated_policy (google.cloud.asset_v1.types.AnalyzerOrgPolicy): + The consolidated policy for the analyzed asset. The + consolidated policy is computed by merging and evaluating + [AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset.policy_bundle][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset.policy_bundle]. + The evaluation will respect the organization policy + `hierarchy + rules `__. + policy_bundle (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy]): + The ordered list of all organization policies from the + [AnalyzeOrgPoliciesResponse.OrgPolicyResult.consolidated_policy.attached_resource][] + to the scope specified in the request. + + If the constraint is defined with default policy, it will + also appear in the list. + """ + + governed_resource: 'AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource' = proto.Field( + proto.MESSAGE, + number=1, + oneof='governed_asset', + message='AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource', + ) + governed_iam_policy: 'AnalyzeOrgPolicyGovernedAssetsResponse.GovernedIamPolicy' = proto.Field( + proto.MESSAGE, + number=2, + oneof='governed_asset', + message='AnalyzeOrgPolicyGovernedAssetsResponse.GovernedIamPolicy', + ) + consolidated_policy: 'AnalyzerOrgPolicy' = proto.Field( + proto.MESSAGE, + number=3, + message='AnalyzerOrgPolicy', + ) + policy_bundle: MutableSequence['AnalyzerOrgPolicy'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='AnalyzerOrgPolicy', + ) + + @property + def raw_page(self): + return self + + governed_assets: MutableSequence[GovernedAsset] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=GovernedAsset, + ) + constraint: 'AnalyzerOrgPolicyConstraint' = proto.Field( + proto.MESSAGE, + number=2, + message='AnalyzerOrgPolicyConstraint', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py b/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py new file mode 100644 index 00000000..e1a65567 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py @@ -0,0 +1,1683 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore +from google.cloud.osconfig_v1.types import inventory +from google.iam.v1 import policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_level_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1', + manifest={ + 'TemporalAsset', + 'TimeWindow', + 'Asset', + 'Resource', + 'RelatedAssets', + 'RelationshipAttributes', + 'RelatedAsset', + 'Tag', + 'EffectiveTagDetails', + 'ResourceSearchResult', + 'VersionedResource', + 'AttachedResource', + 'RelatedResources', + 'RelatedResource', + 'IamPolicySearchResult', + 'IamPolicyAnalysisState', + 'ConditionEvaluation', + 'IamPolicyAnalysisResult', + }, +) + + +class TemporalAsset(proto.Message): + r"""An asset in Google Cloud and its temporal metadata, including + the time window when it was observed and its status during that + window. + + Attributes: + window (google.cloud.asset_v1.types.TimeWindow): + The time window when the asset data and state + was observed. + deleted (bool): + Whether the asset has been deleted or not. + asset (google.cloud.asset_v1.types.Asset): + An asset in Google Cloud. + prior_asset_state (google.cloud.asset_v1.types.TemporalAsset.PriorAssetState): + State of prior_asset. + prior_asset (google.cloud.asset_v1.types.Asset): + Prior copy of the asset. Populated if prior_asset_state is + PRESENT. Currently this is only set for responses in + Real-Time Feed. + """ + class PriorAssetState(proto.Enum): + r"""State of prior asset. + + Values: + PRIOR_ASSET_STATE_UNSPECIFIED (0): + prior_asset is not applicable for the current asset. + PRESENT (1): + prior_asset is populated correctly. + INVALID (2): + Failed to set prior_asset. + DOES_NOT_EXIST (3): + Current asset is the first known state. + DELETED (4): + prior_asset is a deletion. + """ + PRIOR_ASSET_STATE_UNSPECIFIED = 0 + PRESENT = 1 + INVALID = 2 + DOES_NOT_EXIST = 3 + DELETED = 4 + + window: 'TimeWindow' = proto.Field( + proto.MESSAGE, + number=1, + message='TimeWindow', + ) + deleted: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset: 'Asset' = proto.Field( + proto.MESSAGE, + number=3, + message='Asset', + ) + prior_asset_state: PriorAssetState = proto.Field( + proto.ENUM, + number=4, + enum=PriorAssetState, + ) + prior_asset: 'Asset' = proto.Field( + proto.MESSAGE, + number=5, + message='Asset', + ) + + +class TimeWindow(proto.Message): + r"""A time window specified by its ``start_time`` and ``end_time``. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of the time window (exclusive). + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the time window (inclusive). If + not specified, the current timestamp is used + instead. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Asset(proto.Message): + r"""An asset in Google Cloud. An asset can be any resource in the Google + Cloud `resource + hierarchy `__, + a resource outside the Google Cloud resource hierarchy (such as + Google Kubernetes Engine clusters and objects), or a policy (e.g. + IAM policy), or a relationship (e.g. an INSTANCE_TO_INSTANCEGROUP + relationship). See `Supported asset + types `__ + for more information. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update timestamp of an asset. update_time is + updated when create/update/delete operation is performed. + name (str): + The full name of the asset. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`` + + See `Resource + names `__ + for more information. + asset_type (str): + The type of the asset. Example: + ``compute.googleapis.com/Disk`` + + See `Supported asset + types `__ + for more information. + resource (google.cloud.asset_v1.types.Resource): + A representation of the resource. + iam_policy (google.iam.v1.policy_pb2.Policy): + A representation of the IAM policy set on a Google Cloud + resource. There can be a maximum of one IAM policy set on + any given resource. In addition, IAM policies inherit their + granted access scope from any policies set on parent + resources in the resource hierarchy. Therefore, the + effectively policy is the union of both the policy set on + this resource and each policy set on all of the resource's + ancestry resource levels in the hierarchy. See `this + topic `__ + for more information. + org_policy (MutableSequence[google.cloud.orgpolicy.v1.orgpolicy_pb2.Policy]): + A representation of an `organization + policy `__. + There can be more than one organization policy with + different constraints set on a given resource. + access_policy (google.identity.accesscontextmanager.v1.access_policy_pb2.AccessPolicy): + Please also refer to the `access policy user + guide `__. + + This field is a member of `oneof`_ ``access_context_policy``. + access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): + Please also refer to the `access level user + guide `__. + + This field is a member of `oneof`_ ``access_context_policy``. + service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): + Please also refer to the `service perimeter user + guide `__. + + This field is a member of `oneof`_ ``access_context_policy``. + os_inventory (google.cloud.osconfig_v1.types.Inventory): + A representation of runtime OS Inventory information. See + `this + topic `__ + for more information. + related_assets (google.cloud.asset_v1.types.RelatedAssets): + DEPRECATED. This field only presents for the + purpose of backward-compatibility. The server + will never generate responses with this field. + The related assets of the asset of one + relationship type. One asset only represents one + type of relationship. + related_asset (google.cloud.asset_v1.types.RelatedAsset): + One related asset of the current asset. + ancestors (MutableSequence[str]): + The ancestry path of an asset in Google Cloud `resource + hierarchy `__, + represented as a list of relative resource names. An + ancestry path starts with the closest ancestor in the + hierarchy and ends at root. If the asset is a project, + folder, or organization, the ancestry path starts from the + asset itself. + + Example: + ``["projects/123456789", "folders/5432", "organizations/1234"]`` + """ + + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource: 'Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='Resource', + ) + iam_policy: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + org_policy: MutableSequence[orgpolicy_pb2.Policy] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=orgpolicy_pb2.Policy, + ) + access_policy: access_policy_pb2.AccessPolicy = proto.Field( + proto.MESSAGE, + number=7, + oneof='access_context_policy', + message=access_policy_pb2.AccessPolicy, + ) + access_level: access_level_pb2.AccessLevel = proto.Field( + proto.MESSAGE, + number=8, + oneof='access_context_policy', + message=access_level_pb2.AccessLevel, + ) + service_perimeter: service_perimeter_pb2.ServicePerimeter = proto.Field( + proto.MESSAGE, + number=9, + oneof='access_context_policy', + message=service_perimeter_pb2.ServicePerimeter, + ) + os_inventory: inventory.Inventory = proto.Field( + proto.MESSAGE, + number=12, + message=inventory.Inventory, + ) + related_assets: 'RelatedAssets' = proto.Field( + proto.MESSAGE, + number=13, + message='RelatedAssets', + ) + related_asset: 'RelatedAsset' = proto.Field( + proto.MESSAGE, + number=15, + message='RelatedAsset', + ) + ancestors: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + + +class Resource(proto.Message): + r"""A representation of a Google Cloud resource. + + Attributes: + version (str): + The API version. Example: ``v1`` + discovery_document_uri (str): + The URL of the discovery document containing the resource's + JSON schema. Example: + ``https://www.googleapis.com/discovery/v1/apis/compute/v1/rest`` + + This value is unspecified for resources that do not have an + API based on a discovery document, such as Cloud Bigtable. + discovery_name (str): + The JSON schema name listed in the discovery document. + Example: ``Project`` + + This value is unspecified for resources that do not have an + API based on a discovery document, such as Cloud Bigtable. + resource_url (str): + The REST URL for accessing the resource. An HTTP ``GET`` + request using this URL returns the resource itself. Example: + ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`` + + This value is unspecified for resources without a REST API. + parent (str): + The full name of the immediate parent of this resource. See + `Resource + Names `__ + for more information. + + For Google Cloud assets, this value is the parent resource + defined in the `IAM policy + hierarchy `__. + Example: + ``//cloudresourcemanager.googleapis.com/projects/my_project_123`` + + For third-party assets, this field may be set differently. + data (google.protobuf.struct_pb2.Struct): + The content of the resource, in which some + sensitive fields are removed and may not be + present. + location (str): + The location of the resource in Google Cloud, + such as its zone and region. For more + information, see + https://cloud.google.com/about/locations/. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + discovery_document_uri: str = proto.Field( + proto.STRING, + number=2, + ) + discovery_name: str = proto.Field( + proto.STRING, + number=3, + ) + resource_url: str = proto.Field( + proto.STRING, + number=4, + ) + parent: str = proto.Field( + proto.STRING, + number=5, + ) + data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + location: str = proto.Field( + proto.STRING, + number=8, + ) + + +class RelatedAssets(proto.Message): + r"""DEPRECATED. This message only presents for the purpose of + backward-compatibility. The server will never populate this message + in responses. The detailed related assets with the + ``relationship_type``. + + Attributes: + relationship_attributes (google.cloud.asset_v1.types.RelationshipAttributes): + The detailed relationship attributes. + assets (MutableSequence[google.cloud.asset_v1.types.RelatedAsset]): + The peer resources of the relationship. + """ + + relationship_attributes: 'RelationshipAttributes' = proto.Field( + proto.MESSAGE, + number=1, + message='RelationshipAttributes', + ) + assets: MutableSequence['RelatedAsset'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='RelatedAsset', + ) + + +class RelationshipAttributes(proto.Message): + r"""DEPRECATED. This message only presents for the purpose of + backward-compatibility. The server will never populate this message + in responses. The relationship attributes which include ``type``, + ``source_resource_type``, ``target_resource_type`` and ``action``. + + Attributes: + type_ (str): + The unique identifier of the relationship type. Example: + ``INSTANCE_TO_INSTANCEGROUP`` + source_resource_type (str): + The source asset type. Example: + ``compute.googleapis.com/Instance`` + target_resource_type (str): + The target asset type. Example: + ``compute.googleapis.com/Disk`` + action (str): + The detail of the relationship, e.g. ``contains``, + ``attaches`` + """ + + type_: str = proto.Field( + proto.STRING, + number=4, + ) + source_resource_type: str = proto.Field( + proto.STRING, + number=1, + ) + target_resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + action: str = proto.Field( + proto.STRING, + number=3, + ) + + +class RelatedAsset(proto.Message): + r"""An asset identifier in Google Cloud which contains its name, type + and ancestors. An asset can be any resource in the Google Cloud + `resource + hierarchy `__, + a resource outside the Google Cloud resource hierarchy (such as + Google Kubernetes Engine clusters and objects), or a policy (e.g. + IAM policy). See `Supported asset + types `__ + for more information. + + Attributes: + asset (str): + The full name of the asset. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`` + + See `Resource + names `__ + for more information. + asset_type (str): + The type of the asset. Example: + ``compute.googleapis.com/Disk`` + + See `Supported asset + types `__ + for more information. + ancestors (MutableSequence[str]): + The ancestors of an asset in Google Cloud `resource + hierarchy `__, + represented as a list of relative resource names. An + ancestry path starts with the closest ancestor in the + hierarchy and ends at root. + + Example: + ``["projects/123456789", "folders/5432", "organizations/1234"]`` + relationship_type (str): + The unique identifier of the relationship type. Example: + ``INSTANCE_TO_INSTANCEGROUP`` + """ + + asset: str = proto.Field( + proto.STRING, + number=1, + ) + asset_type: str = proto.Field( + proto.STRING, + number=2, + ) + ancestors: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + relationship_type: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Tag(proto.Message): + r"""The key and value for a + `tag `__, + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tag_key (str): + TagKey namespaced name, in the format of + {ORG_ID}/{TAG_KEY_SHORT_NAME}. + + This field is a member of `oneof`_ ``_tag_key``. + tag_value (str): + TagValue namespaced name, in the format of + {ORG_ID}/{TAG_KEY_SHORT_NAME}/{TAG_VALUE_SHORT_NAME}. + + This field is a member of `oneof`_ ``_tag_value``. + tag_value_id (str): + TagValue ID, in the format of tagValues/{TAG_VALUE_ID}. + + This field is a member of `oneof`_ ``_tag_value_id``. + """ + + tag_key: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + tag_value: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + tag_value_id: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + + +class EffectiveTagDetails(proto.Message): + r"""The effective tags and the ancestor resources from which they + were inherited. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + attached_resource (str): + The `full resource + name `__ + of the ancestor from which an [effective_tag][] is + inherited, according to `tag + inheritance `__. + + This field is a member of `oneof`_ ``_attached_resource``. + effective_tags (MutableSequence[google.cloud.asset_v1.types.Tag]): + The effective tags inherited from the + [attached_resource][google.cloud.asset.v1.EffectiveTagDetails.attached_resource]. + Note that tags with the same key but different values may + attach to resources at a different hierarchy levels. The + lower hierarchy tag value will overwrite the higher + hierarchy tag value of the same tag key. In this case, the + tag value at the higher hierarchy level will be removed. For + more information, see `tag + inheritance `__. + """ + + attached_resource: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + effective_tags: MutableSequence['Tag'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='Tag', + ) + + +class ResourceSearchResult(proto.Message): + r"""A result of Resource Search, containing information of a + cloud resource. Next ID: 34 + + Attributes: + name (str): + The full resource name of this resource. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Cloud Asset Inventory Resource Name + Format `__ + for more information. + + To search against the ``name``: + + - Use a field query. Example: ``name:instance1`` + - Use a free text query. Example: ``instance1`` + asset_type (str): + The type of this resource. Example: + ``compute.googleapis.com/Disk``. + + To search against the ``asset_type``: + + - Specify the ``asset_type`` field in your search request. + project (str): + The project that this resource belongs to, in the form of + projects/{PROJECT_NUMBER}. This field is available when the + resource belongs to a project. + + To search against ``project``: + + - Use a field query. Example: ``project:12345`` + - Use a free text query. Example: ``12345`` + - Specify the ``scope`` field as this project in your + search request. + folders (MutableSequence[str]): + The folder(s) that this resource belongs to, in the form of + folders/{FOLDER_NUMBER}. This field is available when the + resource belongs to one or more folders. + + To search against ``folders``: + + - Use a field query. Example: ``folders:(123 OR 456)`` + - Use a free text query. Example: ``123`` + - Specify the ``scope`` field as this folder in your search + request. + organization (str): + The organization that this resource belongs to, in the form + of organizations/{ORGANIZATION_NUMBER}. This field is + available when the resource belongs to an organization. + + To search against ``organization``: + + - Use a field query. Example: ``organization:123`` + - Use a free text query. Example: ``123`` + - Specify the ``scope`` field as this organization in your + search request. + display_name (str): + The display name of this resource. This field is available + only when the resource's Protobuf contains it. + + To search against the ``display_name``: + + - Use a field query. Example: ``displayName:"My Instance"`` + - Use a free text query. Example: ``"My Instance"`` + description (str): + One or more paragraphs of text description of this resource. + Maximum length could be up to 1M bytes. This field is + available only when the resource's Protobuf contains it. + + To search against the ``description``: + + - Use a field query. Example: + ``description:"important instance"`` + - Use a free text query. Example: ``"important instance"`` + location (str): + Location can be ``global``, regional like ``us-east1``, or + zonal like ``us-west1-b``. This field is available only when + the resource's Protobuf contains it. + + To search against the ``location``: + + - Use a field query. Example: ``location:us-west*`` + - Use a free text query. Example: ``us-west*`` + labels (MutableMapping[str, str]): + Labels associated with this resource. See `Labelling and + grouping Google Cloud + resources `__ + for more information. This field is available only when the + resource's Protobuf contains it. + + To search against the ``labels``: + + - Use a field query: + + - query on any label's key or value. Example: + ``labels:prod`` + - query by a given label. Example: ``labels.env:prod`` + - query by a given label's existence. Example: + ``labels.env:*`` + + - Use a free text query. Example: ``prod`` + network_tags (MutableSequence[str]): + Network tags associated with this resource. Like labels, + network tags are a type of annotations used to group Google + Cloud resources. See `Labelling Google Cloud + resources `__ + for more information. This field is available only when the + resource's Protobuf contains it. + + To search against the ``network_tags``: + + - Use a field query. Example: ``networkTags:internal`` + - Use a free text query. Example: ``internal`` + kms_key (str): + The Cloud KMS + `CryptoKey `__ + name or + `CryptoKeyVersion `__ + name. + + This field only presents for the purpose of backward + compatibility. Please use the ``kms_keys`` field to retrieve + Cloud KMS key information. This field is available only when + the resource's Protobuf contains it and will only be + populated for `these resource + types `__ + for backward compatible purposes. + + To search against the ``kms_key``: + + - Use a field query. Example: ``kmsKey:key`` + - Use a free text query. Example: ``key`` + kms_keys (MutableSequence[str]): + The Cloud KMS + `CryptoKey `__ + names or + `CryptoKeyVersion `__ + names. This field is available only when the resource's + Protobuf contains it. + + To search against the ``kms_keys``: + + - Use a field query. Example: ``kmsKeys:key`` + - Use a free text query. Example: ``key`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + The create timestamp of this resource, at which the resource + was created. The granularity is in seconds. Timestamp.nanos + will always be 0. This field is available only when the + resource's Protobuf contains it. + + To search against ``create_time``: + + - Use a field query. + + - value in seconds since unix epoch. Example: + ``createTime > 1609459200`` + - value in date string. Example: + ``createTime > 2021-01-01`` + - value in date-time string (must be quoted). Example: + ``createTime > "2021-01-01T00:00:00"`` + update_time (google.protobuf.timestamp_pb2.Timestamp): + The last update timestamp of this resource, at which the + resource was last modified or deleted. The granularity is in + seconds. Timestamp.nanos will always be 0. This field is + available only when the resource's Protobuf contains it. + + To search against ``update_time``: + + - Use a field query. + + - value in seconds since unix epoch. Example: + ``updateTime < 1609459200`` + - value in date string. Example: + ``updateTime < 2021-01-01`` + - value in date-time string (must be quoted). Example: + ``updateTime < "2021-01-01T00:00:00"`` + state (str): + The state of this resource. Different resources types have + different state definitions that are mapped from various + fields of different resource types. This field is available + only when the resource's Protobuf contains it. + + Example: If the resource is an instance provided by Compute + Engine, its state will include PROVISIONING, STAGING, + RUNNING, STOPPING, SUSPENDING, SUSPENDED, REPAIRING, and + TERMINATED. See ``status`` definition in `API + Reference `__. + If the resource is a project provided by Resource Manager, + its state will include LIFECYCLE_STATE_UNSPECIFIED, ACTIVE, + DELETE_REQUESTED and DELETE_IN_PROGRESS. See + ``lifecycleState`` definition in `API + Reference `__. + + To search against the ``state``: + + - Use a field query. Example: ``state:RUNNING`` + - Use a free text query. Example: ``RUNNING`` + additional_attributes (google.protobuf.struct_pb2.Struct): + The additional searchable attributes of this resource. The + attributes may vary from one resource type to another. + Examples: ``projectId`` for Project, ``dnsName`` for DNS + ManagedZone. This field contains a subset of the resource + metadata fields that are returned by the List or Get APIs + provided by the corresponding Google Cloud service (e.g., + Compute Engine). see `API references and supported + searchable + attributes `__ + to see which fields are included. + + You can search values of these fields through free text + search. However, you should not consume the field + programically as the field names and values may change as + the Google Cloud service updates to a new incompatible API + version. + + To search against the ``additional_attributes``: + + - Use a free text query to match the attributes values. + Example: to search + ``additional_attributes = { dnsName: "foobar" }``, you + can issue a query ``foobar``. + parent_full_resource_name (str): + The full resource name of this resource's parent, if it has + one. To search against the ``parent_full_resource_name``: + + - Use a field query. Example: + ``parentFullResourceName:"project-name"`` + - Use a free text query. Example: ``project-name`` + versioned_resources (MutableSequence[google.cloud.asset_v1.types.VersionedResource]): + Versioned resource representations of this resource. This is + repeated because there could be multiple versions of + resource representations during version migration. + + This ``versioned_resources`` field is not searchable. Some + attributes of the resource representations are exposed in + ``additional_attributes`` field, so as to allow users to + search on them. + attached_resources (MutableSequence[google.cloud.asset_v1.types.AttachedResource]): + Attached resources of this resource. For example, an + OSConfig Inventory is an attached resource of a Compute + Instance. This field is repeated because a resource could + have multiple attached resources. + + This ``attached_resources`` field is not searchable. Some + attributes of the attached resources are exposed in + ``additional_attributes`` field, so as to allow users to + search on them. + relationships (MutableMapping[str, google.cloud.asset_v1.types.RelatedResources]): + A map of related resources of this resource, keyed by the + relationship type. A relationship type is in the format of + {SourceType}*{ACTION}*\ {DestType}. Example: + ``DISK_TO_INSTANCE``, ``DISK_TO_NETWORK``, + ``INSTANCE_TO_INSTANCEGROUP``. See `supported relationship + types `__. + tag_keys (MutableSequence[str]): + This field is only present for the purpose of backward + compatibility. Please use the ``tags`` field instead. + + TagKey namespaced names, in the format of + {ORG_ID}/{TAG_KEY_SHORT_NAME}. To search against the + ``tagKeys``: + + - Use a field query. Example: + + - ``tagKeys:"123456789/env*"`` + - ``tagKeys="123456789/env"`` + - ``tagKeys:"env"`` + + - Use a free text query. Example: + + - ``env`` + tag_values (MutableSequence[str]): + This field is only present for the purpose of backward + compatibility. Please use the ``tags`` field instead. + + TagValue namespaced names, in the format of + {ORG_ID}/{TAG_KEY_SHORT_NAME}/{TAG_VALUE_SHORT_NAME}. To + search against the ``tagValues``: + + - Use a field query. Example: + + - ``tagValues:"env"`` + - ``tagValues:"env/prod"`` + - ``tagValues:"123456789/env/prod*"`` + - ``tagValues="123456789/env/prod"`` + + - Use a free text query. Example: + + - ``prod`` + tag_value_ids (MutableSequence[str]): + This field is only present for the purpose of backward + compatibility. Please use the ``tags`` field instead. + + TagValue IDs, in the format of tagValues/{TAG_VALUE_ID}. To + search against the ``tagValueIds``: + + - Use a field query. Example: + + - ``tagValueIds="tagValues/456"`` + + - Use a free text query. Example: + + - ``456`` + tags (MutableSequence[google.cloud.asset_v1.types.Tag]): + The tags directly attached to this resource. + + To search against the ``tags``: + + - Use a field query. Example: + + - ``tagKeys:"123456789/env*"`` + - ``tagKeys="123456789/env"`` + - ``tagKeys:"env"`` + - ``tagValues:"env"`` + - ``tagValues:"env/prod"`` + - ``tagValues:"123456789/env/prod*"`` + - ``tagValues="123456789/env/prod"`` + - ``tagValueIds="tagValues/456"`` + + - Use a free text query. Example: + + - ``env/prod`` + effective_tags (MutableSequence[google.cloud.asset_v1.types.EffectiveTagDetails]): + The effective tags on this resource. All of the tags that + are both attached to and inherited by a resource are + collectively called the effective tags. For more + information, see `tag + inheritance `__. + + To search against the ``effective_tags``: + + - Use a field query. Example: + + - ``effectiveTagKeys:"123456789/env*"`` + - ``effectiveTagKeys="123456789/env"`` + - ``effectiveTagKeys:"env"`` + - ``effectiveTagValues:"env"`` + - ``effectiveTagValues:"env/prod"`` + - ``effectiveTagValues:"123456789/env/prod*"`` + - ``effectiveTagValues="123456789/env/prod"`` + - ``effectiveTagValueIds="tagValues/456"`` + parent_asset_type (str): + The type of this resource's immediate parent, if there is + one. + + To search against the ``parent_asset_type``: + + - Use a field query. Example: + ``parentAssetType:"cloudresourcemanager.googleapis.com/Project"`` + - Use a free text query. Example: + ``cloudresourcemanager.googleapis.com/Project`` + scc_security_marks (MutableMapping[str, str]): + The actual content of Security Command Center security marks + associated with the asset. + + Note that both staging & prod SecurityMarks are attached on + prod resources. In CAS preprod/prod, both staging & prod + SecurityMarks are ingested and returned in the following + ``security_marks`` map. In that case, the prefix "staging." + will be added to the keys of all the staging marks. To + search against SCC SecurityMarks field: + + - Use a field query: + + - query by a given key value pair. Example: + ``sccSecurityMarks.foo=bar`` + - query by a given key's existence. Example: + ``sccSecurityMarks.foo:*`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_type: str = proto.Field( + proto.STRING, + number=2, + ) + project: str = proto.Field( + proto.STRING, + number=3, + ) + folders: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=17, + ) + organization: str = proto.Field( + proto.STRING, + number=18, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + location: str = proto.Field( + proto.STRING, + number=6, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + network_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + kms_key: str = proto.Field( + proto.STRING, + number=10, + ) + kms_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=28, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + state: str = proto.Field( + proto.STRING, + number=13, + ) + additional_attributes: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + parent_full_resource_name: str = proto.Field( + proto.STRING, + number=19, + ) + versioned_resources: MutableSequence['VersionedResource'] = proto.RepeatedField( + proto.MESSAGE, + number=16, + message='VersionedResource', + ) + attached_resources: MutableSequence['AttachedResource'] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message='AttachedResource', + ) + relationships: MutableMapping[str, 'RelatedResources'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=21, + message='RelatedResources', + ) + tag_keys: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=23, + ) + tag_values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=25, + ) + tag_value_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=26, + ) + tags: MutableSequence['Tag'] = proto.RepeatedField( + proto.MESSAGE, + number=29, + message='Tag', + ) + effective_tags: MutableSequence['EffectiveTagDetails'] = proto.RepeatedField( + proto.MESSAGE, + number=30, + message='EffectiveTagDetails', + ) + parent_asset_type: str = proto.Field( + proto.STRING, + number=103, + ) + scc_security_marks: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=32, + ) + + +class VersionedResource(proto.Message): + r"""Resource representation as defined by the corresponding + service providing the resource for a given API version. + + Attributes: + version (str): + API version of the resource. + + Example: If the resource is an instance provided by Compute + Engine v1 API as defined in + ``https://cloud.google.com/compute/docs/reference/rest/v1/instances``, + version will be "v1". + resource (google.protobuf.struct_pb2.Struct): + JSON representation of the resource as defined by the + corresponding service providing this resource. + + Example: If the resource is an instance provided by Compute + Engine, this field will contain the JSON representation of + the instance as defined by Compute Engine: + ``https://cloud.google.com/compute/docs/reference/rest/v1/instances``. + + You can find the resource definition for each supported + resource type in this table: + ``https://cloud.google.com/asset-inventory/docs/supported-asset-types#searchable_asset_types`` + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + resource: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + + +class AttachedResource(proto.Message): + r"""Attached resource representation, which is defined by the + corresponding service provider. It represents an attached + resource's payload. + + Attributes: + asset_type (str): + The type of this attached resource. + + Example: ``osconfig.googleapis.com/Inventory`` + + You can find the supported attached asset types of each + resource in this table: + ``https://cloud.google.com/asset-inventory/docs/supported-asset-types#searchable_asset_types`` + versioned_resources (MutableSequence[google.cloud.asset_v1.types.VersionedResource]): + Versioned resource representations of this + attached resource. This is repeated because + there could be multiple versions of the attached + resource representations during version + migration. + """ + + asset_type: str = proto.Field( + proto.STRING, + number=1, + ) + versioned_resources: MutableSequence['VersionedResource'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='VersionedResource', + ) + + +class RelatedResources(proto.Message): + r"""The related resources of the primary resource. + + Attributes: + related_resources (MutableSequence[google.cloud.asset_v1.types.RelatedResource]): + The detailed related resources of the primary + resource. + """ + + related_resources: MutableSequence['RelatedResource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='RelatedResource', + ) + + +class RelatedResource(proto.Message): + r"""The detailed related resource. + + Attributes: + asset_type (str): + The type of the asset. Example: + ``compute.googleapis.com/Instance`` + full_resource_name (str): + The full resource name of the related resource. Example: + ``//compute.googleapis.com/projects/my_proj_123/zones/instance/instance123`` + """ + + asset_type: str = proto.Field( + proto.STRING, + number=1, + ) + full_resource_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +class IamPolicySearchResult(proto.Message): + r"""A result of IAM Policy search, containing information of an + IAM policy. + + Attributes: + resource (str): + The full resource name of the resource associated with this + IAM policy. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Cloud Asset Inventory Resource Name + Format `__ + for more information. + + To search against the ``resource``: + + - use a field query. Example: + ``resource:organizations/123`` + asset_type (str): + The type of the resource associated with this IAM policy. + Example: ``compute.googleapis.com/Disk``. + + To search against the ``asset_type``: + + - specify the ``asset_types`` field in your search request. + project (str): + The project that the associated Google Cloud resource + belongs to, in the form of projects/{PROJECT_NUMBER}. If an + IAM policy is set on a resource (like VM instance, Cloud + Storage bucket), the project field will indicate the project + that contains the resource. If an IAM policy is set on a + folder or orgnization, this field will be empty. + + To search against the ``project``: + + - specify the ``scope`` field as this project in your + search request. + folders (MutableSequence[str]): + The folder(s) that the IAM policy belongs to, in the form of + folders/{FOLDER_NUMBER}. This field is available when the + IAM policy belongs to one or more folders. + + To search against ``folders``: + + - use a field query. Example: ``folders:(123 OR 456)`` + - use a free text query. Example: ``123`` + - specify the ``scope`` field as this folder in your search + request. + organization (str): + The organization that the IAM policy belongs to, in the form + of organizations/{ORGANIZATION_NUMBER}. This field is + available when the IAM policy belongs to an organization. + + To search against ``organization``: + + - use a field query. Example: ``organization:123`` + - use a free text query. Example: ``123`` + - specify the ``scope`` field as this organization in your + search request. + policy (google.iam.v1.policy_pb2.Policy): + The IAM policy directly set on the given resource. Note that + the original IAM policy can contain multiple bindings. This + only contains the bindings that match the given query. For + queries that don't contain a constrain on policies (e.g., an + empty query), this contains all the bindings. + + To search against the ``policy`` bindings: + + - use a field query: + + - query by the policy contained members. Example: + ``policy:amy@gmail.com`` + - query by the policy contained roles. Example: + ``policy:roles/compute.admin`` + - query by the policy contained roles' included + permissions. Example: + ``policy.role.permissions:compute.instances.create`` + explanation (google.cloud.asset_v1.types.IamPolicySearchResult.Explanation): + Explanation about the IAM policy search + result. It contains additional information to + explain why the search result matches the query. + """ + + class Explanation(proto.Message): + r"""Explanation about the IAM policy search result. + + Attributes: + matched_permissions (MutableMapping[str, google.cloud.asset_v1.types.IamPolicySearchResult.Explanation.Permissions]): + The map from roles to their included permissions that match + the permission query (i.e., a query containing + ``policy.role.permissions:``). Example: if query + ``policy.role.permissions:compute.disk.get`` matches a + policy binding that contains owner role, the + matched_permissions will be + ``{"roles/owner": ["compute.disk.get"]}``. The roles can + also be found in the returned ``policy`` bindings. Note that + the map is populated only for requests with permission + queries. + """ + + class Permissions(proto.Message): + r"""IAM permissions + + Attributes: + permissions (MutableSequence[str]): + A list of permissions. A sample permission string: + ``compute.disk.get``. + """ + + permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + matched_permissions: MutableMapping[str, 'IamPolicySearchResult.Explanation.Permissions'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='IamPolicySearchResult.Explanation.Permissions', + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + asset_type: str = proto.Field( + proto.STRING, + number=5, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + folders: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + organization: str = proto.Field( + proto.STRING, + number=7, + ) + policy: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=3, + message=policy_pb2.Policy, + ) + explanation: Explanation = proto.Field( + proto.MESSAGE, + number=4, + message=Explanation, + ) + + +class IamPolicyAnalysisState(proto.Message): + r"""Represents the detailed state of an entity under analysis, + such as a resource, an identity or an access. + + Attributes: + code (google.rpc.code_pb2.Code): + The Google standard error code that best describes the + state. For example: + + - OK means the analysis on this entity has been + successfully finished; + - PERMISSION_DENIED means an access denied error is + encountered; + - DEADLINE_EXCEEDED means the analysis on this entity + hasn't been started in time; + cause (str): + The human-readable description of the cause + of failure. + """ + + code: code_pb2.Code = proto.Field( + proto.ENUM, + number=1, + enum=code_pb2.Code, + ) + cause: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ConditionEvaluation(proto.Message): + r"""The Condition evaluation. + + Attributes: + evaluation_value (google.cloud.asset_v1.types.ConditionEvaluation.EvaluationValue): + The evaluation result. + """ + class EvaluationValue(proto.Enum): + r"""Value of this expression. + + Values: + EVALUATION_VALUE_UNSPECIFIED (0): + Reserved for future use. + TRUE (1): + The evaluation result is ``true``. + FALSE (2): + The evaluation result is ``false``. + CONDITIONAL (3): + The evaluation result is ``conditional`` when the condition + expression contains variables that are either missing input + values or have not been supported by Analyzer yet. + """ + EVALUATION_VALUE_UNSPECIFIED = 0 + TRUE = 1 + FALSE = 2 + CONDITIONAL = 3 + + evaluation_value: EvaluationValue = proto.Field( + proto.ENUM, + number=1, + enum=EvaluationValue, + ) + + +class IamPolicyAnalysisResult(proto.Message): + r"""IAM Policy analysis result, consisting of one IAM policy + binding and derived access control lists. + + Attributes: + attached_resource_full_name (str): + The `full resource + name `__ + of the resource to which the + [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] + policy attaches. + iam_binding (google.iam.v1.policy_pb2.Binding): + The IAM policy binding under analysis. + access_control_lists (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.AccessControlList]): + The access control lists derived from the + [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] + that match or potentially match resource and access + selectors specified in the request. + identity_list (google.cloud.asset_v1.types.IamPolicyAnalysisResult.IdentityList): + The identity list derived from members of the + [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] + that match or potentially match identity selector specified + in the request. + fully_explored (bool): + Represents whether all analyses on the + [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] + have successfully finished. + """ + + class Resource(proto.Message): + r"""A Google Cloud resource under analysis. + + Attributes: + full_resource_name (str): + The `full resource + name `__ + analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): + The analysis state of this resource. + """ + + full_resource_name: str = proto.Field( + proto.STRING, + number=1, + ) + analysis_state: 'IamPolicyAnalysisState' = proto.Field( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisState', + ) + + class Access(proto.Message): + r"""An IAM role or permission under analysis. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + role (str): + The role. + + This field is a member of `oneof`_ ``oneof_access``. + permission (str): + The permission. + + This field is a member of `oneof`_ ``oneof_access``. + analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): + The analysis state of this access. + """ + + role: str = proto.Field( + proto.STRING, + number=1, + oneof='oneof_access', + ) + permission: str = proto.Field( + proto.STRING, + number=2, + oneof='oneof_access', + ) + analysis_state: 'IamPolicyAnalysisState' = proto.Field( + proto.MESSAGE, + number=3, + message='IamPolicyAnalysisState', + ) + + class Identity(proto.Message): + r"""An identity under analysis. + + Attributes: + name (str): + The identity of members, formatted as appear in an `IAM + policy + binding `__. + For example, they might be formatted like the following: + + - user:foo@google.com + - group:group1@google.com + - serviceAccount:s1@prj1.iam.gserviceaccount.com + - projectOwner:some_project_id + - domain:google.com + - allUsers + analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): + The analysis state of this identity. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + analysis_state: 'IamPolicyAnalysisState' = proto.Field( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisState', + ) + + class Edge(proto.Message): + r"""A directional edge. + + Attributes: + source_node (str): + The source node of the edge. For example, it + could be a full resource name for a resource + node or an email of an identity. + target_node (str): + The target node of the edge. For example, it + could be a full resource name for a resource + node or an email of an identity. + """ + + source_node: str = proto.Field( + proto.STRING, + number=1, + ) + target_node: str = proto.Field( + proto.STRING, + number=2, + ) + + class AccessControlList(proto.Message): + r"""An access control list, derived from the above IAM policy binding, + which contains a set of resources and accesses. May include one item + from each set to compose an access control entry. + + NOTICE that there could be multiple access control lists for one IAM + policy binding. The access control lists are created based on + resource and access combinations. + + For example, assume we have the following cases in one IAM policy + binding: + + - Permission P1 and P2 apply to resource R1 and R2; + - Permission P3 applies to resource R2 and R3; + + This will result in the following access control lists: + + - AccessControlList 1: [R1, R2], [P1, P2] + - AccessControlList 2: [R2, R3], [P3] + + Attributes: + resources (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Resource]): + The resources that match one of the following conditions: + + - The resource_selector, if it is specified in request; + - Otherwise, resources reachable from the policy attached + resource. + accesses (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Access]): + The accesses that match one of the following conditions: + + - The access_selector, if it is specified in request; + - Otherwise, access specifiers reachable from the policy + binding's role. + resource_edges (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Edge]): + Resource edges of the graph starting from the policy + attached resource to any descendant resources. The + [Edge.source_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.source_node] + contains the full resource name of a parent resource and + [Edge.target_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.target_node] + contains the full resource name of a child resource. This + field is present only if the output_resource_edges option is + enabled in request. + condition_evaluation (google.cloud.asset_v1.types.ConditionEvaluation): + Condition evaluation for this + AccessControlList, if there is a condition + defined in the above IAM policy binding. + """ + + resources: MutableSequence['IamPolicyAnalysisResult.Resource'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisResult.Resource', + ) + accesses: MutableSequence['IamPolicyAnalysisResult.Access'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.Access', + ) + resource_edges: MutableSequence['IamPolicyAnalysisResult.Edge'] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='IamPolicyAnalysisResult.Edge', + ) + condition_evaluation: 'ConditionEvaluation' = proto.Field( + proto.MESSAGE, + number=4, + message='ConditionEvaluation', + ) + + class IdentityList(proto.Message): + r"""The identities and group edges. + + Attributes: + identities (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Identity]): + Only the identities that match one of the following + conditions will be presented: + + - The identity_selector, if it is specified in request; + - Otherwise, identities reachable from the policy binding's + members. + group_edges (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Edge]): + Group identity edges of the graph starting from the + binding's group members to any node of the + [identities][google.cloud.asset.v1.IamPolicyAnalysisResult.IdentityList.identities]. + The + [Edge.source_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.source_node] + contains a group, such as ``group:parent@google.com``. The + [Edge.target_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.target_node] + contains a member of the group, such as + ``group:child@google.com`` or ``user:foo@google.com``. This + field is present only if the output_group_edges option is + enabled in request. + """ + + identities: MutableSequence['IamPolicyAnalysisResult.Identity'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisResult.Identity', + ) + group_edges: MutableSequence['IamPolicyAnalysisResult.Edge'] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.Edge', + ) + + attached_resource_full_name: str = proto.Field( + proto.STRING, + number=1, + ) + iam_binding: policy_pb2.Binding = proto.Field( + proto.MESSAGE, + number=2, + message=policy_pb2.Binding, + ) + access_control_lists: MutableSequence[AccessControlList] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AccessControlList, + ) + identity_list: IdentityList = proto.Field( + proto.MESSAGE, + number=4, + message=IdentityList, + ) + fully_explored: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +__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 00000000..574c5aed --- /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 00000000..c333de24 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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/asset_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==7.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/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py new file mode 100644 index 00000000..4a13b281 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeIamPolicy +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_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 asset_v1 + + +async def sample_analyze_iam_policy(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + request = asset_v1.AnalyzeIamPolicyRequest( + analysis_query=analysis_query, + ) + + # Make the request + response = await client.analyze_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py new file mode 100644 index 00000000..47fb7196 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeIamPolicyLongrunning +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_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 asset_v1 + + +async def sample_analyze_iam_policy_longrunning(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + output_config = asset_v1.IamPolicyAnalysisOutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.AnalyzeIamPolicyLongrunningRequest( + analysis_query=analysis_query, + output_config=output_config, + ) + + # Make the request + operation = client.analyze_iam_policy_longrunning(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py new file mode 100644 index 00000000..5f29caec --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeIamPolicyLongrunning +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_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 asset_v1 + + +def sample_analyze_iam_policy_longrunning(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + output_config = asset_v1.IamPolicyAnalysisOutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.AnalyzeIamPolicyLongrunningRequest( + analysis_query=analysis_query, + output_config=output_config, + ) + + # Make the request + operation = client.analyze_iam_policy_longrunning(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py new file mode 100644 index 00000000..c2aa7028 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeIamPolicy +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_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 asset_v1 + + +def sample_analyze_iam_policy(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + analysis_query = asset_v1.IamPolicyAnalysisQuery() + analysis_query.scope = "scope_value" + + request = asset_v1.AnalyzeIamPolicyRequest( + analysis_query=analysis_query, + ) + + # Make the request + response = client.analyze_iam_policy(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py new file mode 100644 index 00000000..377f2e12 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeMove +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeMove_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 asset_v1 + + +async def sample_analyze_move(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeMoveRequest( + resource="resource_value", + destination_parent="destination_parent_value", + ) + + # Make the request + response = await client.analyze_move(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeMove_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py new file mode 100644 index 00000000..5ec453c1 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeMove +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeMove_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 asset_v1 + + +def sample_analyze_move(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeMoveRequest( + resource="resource_value", + destination_parent="destination_parent_value", + ) + + # Make the request + response = client.analyze_move(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeMove_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py new file mode 100644 index 00000000..625f3dec --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeOrgPolicies +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_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 asset_v1 + + +async def sample_analyze_org_policies(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPoliciesRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py new file mode 100644 index 00000000..892f5a15 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeOrgPolicies +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_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 asset_v1 + + +def sample_analyze_org_policies(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPoliciesRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py new file mode 100644 index 00000000..81b67efb --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeOrgPolicyGovernedAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_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 asset_v1 + + +async def sample_analyze_org_policy_governed_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py new file mode 100644 index 00000000..86aca87d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeOrgPolicyGovernedAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_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 asset_v1 + + +def sample_analyze_org_policy_governed_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py new file mode 100644 index 00000000..3a24500e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeOrgPolicyGovernedContainers +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_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 asset_v1 + + +async def sample_analyze_org_policy_governed_containers(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_containers(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py new file mode 100644 index 00000000..4aa243c9 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AnalyzeOrgPolicyGovernedContainers +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_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 asset_v1 + + +def sample_analyze_org_policy_governed_containers(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( + scope="scope_value", + constraint="constraint_value", + ) + + # Make the request + page_result = client.analyze_org_policy_governed_containers(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py new file mode 100644 index 00000000..6dd1e1dc --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchGetAssetsHistory +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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 asset_v1 + + +async def sample_batch_get_assets_history(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetAssetsHistoryRequest( + parent="parent_value", + ) + + # Make the request + response = await client.batch_get_assets_history(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py new file mode 100644 index 00000000..87e233fb --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchGetAssetsHistory +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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 asset_v1 + + +def sample_batch_get_assets_history(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetAssetsHistoryRequest( + parent="parent_value", + ) + + # Make the request + response = client.batch_get_assets_history(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py new file mode 100644 index 00000000..30ef0c4e --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchGetEffectiveIamPolicies +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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 asset_v1 + + +async def sample_batch_get_effective_iam_policies(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetEffectiveIamPoliciesRequest( + scope="scope_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = await client.batch_get_effective_iam_policies(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py new file mode 100644 index 00000000..f64e953a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchGetEffectiveIamPolicies +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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 asset_v1 + + +def sample_batch_get_effective_iam_policies(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.BatchGetEffectiveIamPoliciesRequest( + scope="scope_value", + names=['names_value1', 'names_value2'], + ) + + # Make the request + response = client.batch_get_effective_iam_policies(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py new file mode 100644 index 00000000..f5aaf9a0 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_CreateFeed_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 asset_v1 + + +async def sample_create_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = await client.create_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_CreateFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py new file mode 100644 index 00000000..4ef06854 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_CreateFeed_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 asset_v1 + + +def sample_create_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = client.create_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_CreateFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py new file mode 100644 index 00000000..b495af66 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_CreateSavedQuery_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 asset_v1 + + +async def sample_create_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.CreateSavedQueryRequest( + parent="parent_value", + saved_query_id="saved_query_id_value", + ) + + # Make the request + response = await client.create_saved_query(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_CreateSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py new file mode 100644 index 00000000..bdebace2 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_CreateSavedQuery_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 asset_v1 + + +def sample_create_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.CreateSavedQueryRequest( + parent="parent_value", + saved_query_id="saved_query_id_value", + ) + + # Make the request + response = client.create_saved_query(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_CreateSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py new file mode 100644 index 00000000..cd3fab7c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_DeleteFeed_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 asset_v1 + + +async def sample_delete_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + await client.delete_feed(request=request) + + +# [END cloudasset_v1_generated_AssetService_DeleteFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py new file mode 100644 index 00000000..b6edad9d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_DeleteFeed_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 asset_v1 + + +def sample_delete_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + client.delete_feed(request=request) + + +# [END cloudasset_v1_generated_AssetService_DeleteFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py new file mode 100644 index 00000000..40cdf7f6 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_DeleteSavedQuery_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 asset_v1 + + +async def sample_delete_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.DeleteSavedQueryRequest( + name="name_value", + ) + + # Make the request + await client.delete_saved_query(request=request) + + +# [END cloudasset_v1_generated_AssetService_DeleteSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py new file mode 100644 index 00000000..29d2ed16 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_DeleteSavedQuery_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 asset_v1 + + +def sample_delete_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.DeleteSavedQueryRequest( + name="name_value", + ) + + # Make the request + client.delete_saved_query(request=request) + + +# [END cloudasset_v1_generated_AssetService_DeleteSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py new file mode 100644 index 00000000..bc593077 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ExportAssets_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 asset_v1 + + +async def sample_export_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + output_config = asset_v1.OutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.ExportAssetsRequest( + parent="parent_value", + output_config=output_config, + ) + + # Make the request + operation = client.export_assets(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_ExportAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py new file mode 100644 index 00000000..0e402bbf --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ExportAssets_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 asset_v1 + + +def sample_export_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + output_config = asset_v1.OutputConfig() + output_config.gcs_destination.uri = "uri_value" + + request = asset_v1.ExportAssetsRequest( + parent="parent_value", + output_config=output_config, + ) + + # Make the request + operation = client.export_assets(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_ExportAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py new file mode 100644 index 00000000..75bdd2fd --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_GetFeed_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 asset_v1 + + +async def sample_get_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = await client.get_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_GetFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py new file mode 100644 index 00000000..01cd552c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_GetFeed_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 asset_v1 + + +def sample_get_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = client.get_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_GetFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py new file mode 100644 index 00000000..7f218510 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_GetSavedQuery_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 asset_v1 + + +async def sample_get_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.GetSavedQueryRequest( + name="name_value", + ) + + # Make the request + response = await client.get_saved_query(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_GetSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py new file mode 100644 index 00000000..947c761d --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_GetSavedQuery_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 asset_v1 + + +def sample_get_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.GetSavedQueryRequest( + name="name_value", + ) + + # Make the request + response = client.get_saved_query(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_GetSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py new file mode 100644 index 00000000..91bc6e83 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ListAssets_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 asset_v1 + + +async def sample_list_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_ListAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py new file mode 100644 index 00000000..cbd05991 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ListAssets_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 asset_v1 + + +def sample_list_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_ListAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py new file mode 100644 index 00000000..52059178 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFeeds +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ListFeeds_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 asset_v1 + + +async def sample_list_feeds(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_feeds(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_ListFeeds_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py new file mode 100644 index 00000000..2c516167 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFeeds +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ListFeeds_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 asset_v1 + + +def sample_list_feeds(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_feeds(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_ListFeeds_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py new file mode 100644 index 00000000..c4be56a4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSavedQueries +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ListSavedQueries_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 asset_v1 + + +async def sample_list_saved_queries(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.ListSavedQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_saved_queries(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_ListSavedQueries_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py new file mode 100644 index 00000000..9825502a --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListSavedQueries +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_ListSavedQueries_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 asset_v1 + + +def sample_list_saved_queries(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.ListSavedQueriesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_saved_queries(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_ListSavedQueries_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py new file mode 100644 index 00000000..bd68125c --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_QueryAssets_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 asset_v1 + + +async def sample_query_assets(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.QueryAssetsRequest( + statement="statement_value", + parent="parent_value", + ) + + # Make the request + response = await client.query_assets(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_QueryAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py new file mode 100644 index 00000000..e64414fd --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for QueryAssets +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_QueryAssets_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 asset_v1 + + +def sample_query_assets(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.QueryAssetsRequest( + statement="statement_value", + parent="parent_value", + ) + + # Make the request + response = client.query_assets(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_QueryAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py new file mode 100644 index 00000000..f99c4503 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllIamPolicies +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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 asset_v1 + + +async def sample_search_all_iam_policies(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_SearchAllIamPolicies_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py new file mode 100644 index 00000000..2095ee02 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllIamPolicies +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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 asset_v1 + + +def sample_search_all_iam_policies(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_SearchAllIamPolicies_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py new file mode 100644 index 00000000..6e228419 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllResources +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_SearchAllResources_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 asset_v1 + + +async def sample_search_all_resources(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_SearchAllResources_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py new file mode 100644 index 00000000..4a82b7eb --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllResources +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_SearchAllResources_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 asset_v1 + + +def sample_search_all_resources(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1_generated_AssetService_SearchAllResources_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py new file mode 100644 index 00000000..80d4dca4 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_UpdateFeed_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 asset_v1 + + +async def sample_update_feed(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = await client.update_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_UpdateFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py new file mode 100644 index 00000000..da3483f2 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFeed +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_UpdateFeed_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 asset_v1 + + +def sample_update_feed(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1.Feed() + feed.name = "name_value" + + request = asset_v1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = client.update_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_UpdateFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py new file mode 100644 index 00000000..56aaab9f --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_UpdateSavedQuery_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 asset_v1 + + +async def sample_update_saved_query(): + # Create a client + client = asset_v1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1.UpdateSavedQueryRequest( + ) + + # Make the request + response = await client.update_saved_query(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_UpdateSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py new file mode 100644 index 00000000..ef6a45d6 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateSavedQuery +# 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-asset + + +# [START cloudasset_v1_generated_AssetService_UpdateSavedQuery_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 asset_v1 + + +def sample_update_saved_query(): + # Create a client + client = asset_v1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1.UpdateSavedQueryRequest( + ) + + # Make the request + response = client.update_saved_query(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1_generated_AssetService_UpdateSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json new file mode 100644 index 00000000..5a90dfa8 --- /dev/null +++ b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json @@ -0,0 +1,3746 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.asset.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-asset", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_iam_policy_longrunning", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeIamPolicyLongrunning" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest" + }, + { + "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": "analyze_iam_policy_longrunning" + }, + "description": "Sample for AnalyzeIamPolicyLongrunning", + "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_iam_policy_longrunning", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeIamPolicyLongrunning" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest" + }, + { + "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": "analyze_iam_policy_longrunning" + }, + "description": "Sample for AnalyzeIamPolicyLongrunning", + "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_iam_policy", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicy", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.AnalyzeIamPolicyResponse", + "shortName": "analyze_iam_policy" + }, + "description": "Sample for AnalyzeIamPolicy", + "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_iam_policy", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicy", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeIamPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.AnalyzeIamPolicyResponse", + "shortName": "analyze_iam_policy" + }, + "description": "Sample for AnalyzeIamPolicy", + "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_move", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeMove", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeMove" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeMoveRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.AnalyzeMoveResponse", + "shortName": "analyze_move" + }, + "description": "Sample for AnalyzeMove", + "file": "cloudasset_v1_generated_asset_service_analyze_move_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeMove_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": "cloudasset_v1_generated_asset_service_analyze_move_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_move", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeMove", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeMove" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeMoveRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.AnalyzeMoveResponse", + "shortName": "analyze_move" + }, + "description": "Sample for AnalyzeMove", + "file": "cloudasset_v1_generated_asset_service_analyze_move_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeMove_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": "cloudasset_v1_generated_asset_service_analyze_move_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_org_policies", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeOrgPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "constraint", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesAsyncPager", + "shortName": "analyze_org_policies" + }, + "description": "Sample for AnalyzeOrgPolicies", + "file": "cloudasset_v1_generated_asset_service_analyze_org_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_org_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_org_policies", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeOrgPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "constraint", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesPager", + "shortName": "analyze_org_policies" + }, + "description": "Sample for AnalyzeOrgPolicies", + "file": "cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_org_policy_governed_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeOrgPolicyGovernedAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "constraint", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager", + "shortName": "analyze_org_policy_governed_assets" + }, + "description": "Sample for AnalyzeOrgPolicyGovernedAssets", + "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_org_policy_governed_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeOrgPolicyGovernedAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "constraint", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsPager", + "shortName": "analyze_org_policy_governed_assets" + }, + "description": "Sample for AnalyzeOrgPolicyGovernedAssets", + "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_org_policy_governed_containers", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeOrgPolicyGovernedContainers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "constraint", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager", + "shortName": "analyze_org_policy_governed_containers" + }, + "description": "Sample for AnalyzeOrgPolicyGovernedContainers", + "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_org_policy_governed_containers", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "AnalyzeOrgPolicyGovernedContainers" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "constraint", + "type": "str" + }, + { + "name": "filter", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersPager", + "shortName": "analyze_org_policy_governed_containers" + }, + "description": "Sample for AnalyzeOrgPolicyGovernedContainers", + "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.batch_get_assets_history", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.BatchGetAssetsHistory", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "BatchGetAssetsHistory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse", + "shortName": "batch_get_assets_history" + }, + "description": "Sample for BatchGetAssetsHistory", + "file": "cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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": "cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.batch_get_assets_history", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.BatchGetAssetsHistory", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "BatchGetAssetsHistory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse", + "shortName": "batch_get_assets_history" + }, + "description": "Sample for BatchGetAssetsHistory", + "file": "cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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": "cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.batch_get_effective_iam_policies", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "BatchGetEffectiveIamPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse", + "shortName": "batch_get_effective_iam_policies" + }, + "description": "Sample for BatchGetEffectiveIamPolicies", + "file": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.batch_get_effective_iam_policies", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "BatchGetEffectiveIamPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse", + "shortName": "batch_get_effective_iam_policies" + }, + "description": "Sample for BatchGetEffectiveIamPolicies", + "file": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.create_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.CreateFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "CreateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.CreateFeedRequest" + }, + { + "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.asset_v1.types.Feed", + "shortName": "create_feed" + }, + "description": "Sample for CreateFeed", + "file": "cloudasset_v1_generated_asset_service_create_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_CreateFeed_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_create_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.create_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.CreateFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "CreateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.CreateFeedRequest" + }, + { + "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.asset_v1.types.Feed", + "shortName": "create_feed" + }, + "description": "Sample for CreateFeed", + "file": "cloudasset_v1_generated_asset_service_create_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_CreateFeed_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_create_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.create_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.CreateSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "CreateSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.CreateSavedQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "saved_query", + "type": "google.cloud.asset_v1.types.SavedQuery" + }, + { + "name": "saved_query_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.asset_v1.types.SavedQuery", + "shortName": "create_saved_query" + }, + "description": "Sample for CreateSavedQuery", + "file": "cloudasset_v1_generated_asset_service_create_saved_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_CreateSavedQuery_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": "cloudasset_v1_generated_asset_service_create_saved_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.create_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.CreateSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "CreateSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.CreateSavedQueryRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "saved_query", + "type": "google.cloud.asset_v1.types.SavedQuery" + }, + { + "name": "saved_query_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.asset_v1.types.SavedQuery", + "shortName": "create_saved_query" + }, + "description": "Sample for CreateSavedQuery", + "file": "cloudasset_v1_generated_asset_service_create_saved_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_CreateSavedQuery_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": "cloudasset_v1_generated_asset_service_create_saved_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.delete_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.DeleteFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "DeleteFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.DeleteFeedRequest" + }, + { + "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_feed" + }, + "description": "Sample for DeleteFeed", + "file": "cloudasset_v1_generated_asset_service_delete_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_DeleteFeed_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": "cloudasset_v1_generated_asset_service_delete_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.delete_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.DeleteFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "DeleteFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.DeleteFeedRequest" + }, + { + "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_feed" + }, + "description": "Sample for DeleteFeed", + "file": "cloudasset_v1_generated_asset_service_delete_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_DeleteFeed_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": "cloudasset_v1_generated_asset_service_delete_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.delete_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.DeleteSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "DeleteSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.DeleteSavedQueryRequest" + }, + { + "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_saved_query" + }, + "description": "Sample for DeleteSavedQuery", + "file": "cloudasset_v1_generated_asset_service_delete_saved_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_DeleteSavedQuery_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": "cloudasset_v1_generated_asset_service_delete_saved_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.delete_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.DeleteSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "DeleteSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.DeleteSavedQueryRequest" + }, + { + "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_saved_query" + }, + "description": "Sample for DeleteSavedQuery", + "file": "cloudasset_v1_generated_asset_service_delete_saved_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_DeleteSavedQuery_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": "cloudasset_v1_generated_asset_service_delete_saved_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.export_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ExportAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ExportAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ExportAssetsRequest" + }, + { + "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": "export_assets" + }, + "description": "Sample for ExportAssets", + "file": "cloudasset_v1_generated_asset_service_export_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ExportAssets_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_export_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.export_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ExportAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ExportAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ExportAssetsRequest" + }, + { + "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": "export_assets" + }, + "description": "Sample for ExportAssets", + "file": "cloudasset_v1_generated_asset_service_export_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ExportAssets_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_export_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.get_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.GetFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "GetFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.GetFeedRequest" + }, + { + "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.asset_v1.types.Feed", + "shortName": "get_feed" + }, + "description": "Sample for GetFeed", + "file": "cloudasset_v1_generated_asset_service_get_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_GetFeed_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": "cloudasset_v1_generated_asset_service_get_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.get_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.GetFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "GetFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.GetFeedRequest" + }, + { + "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.asset_v1.types.Feed", + "shortName": "get_feed" + }, + "description": "Sample for GetFeed", + "file": "cloudasset_v1_generated_asset_service_get_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_GetFeed_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": "cloudasset_v1_generated_asset_service_get_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.get_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.GetSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "GetSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.GetSavedQueryRequest" + }, + { + "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.asset_v1.types.SavedQuery", + "shortName": "get_saved_query" + }, + "description": "Sample for GetSavedQuery", + "file": "cloudasset_v1_generated_asset_service_get_saved_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_GetSavedQuery_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": "cloudasset_v1_generated_asset_service_get_saved_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.get_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.GetSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "GetSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.GetSavedQueryRequest" + }, + { + "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.asset_v1.types.SavedQuery", + "shortName": "get_saved_query" + }, + "description": "Sample for GetSavedQuery", + "file": "cloudasset_v1_generated_asset_service_get_saved_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_GetSavedQuery_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": "cloudasset_v1_generated_asset_service_get_saved_query_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ListAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ListAssetsRequest" + }, + { + "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.asset_v1.services.asset_service.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "cloudasset_v1_generated_asset_service_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ListAssets_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": "cloudasset_v1_generated_asset_service_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.list_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ListAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ListAssetsRequest" + }, + { + "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.asset_v1.services.asset_service.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "cloudasset_v1_generated_asset_service_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ListAssets_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": "cloudasset_v1_generated_asset_service_list_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.list_feeds", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ListFeeds", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListFeeds" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ListFeedsRequest" + }, + { + "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.asset_v1.types.ListFeedsResponse", + "shortName": "list_feeds" + }, + "description": "Sample for ListFeeds", + "file": "cloudasset_v1_generated_asset_service_list_feeds_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ListFeeds_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": "cloudasset_v1_generated_asset_service_list_feeds_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.list_feeds", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ListFeeds", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListFeeds" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ListFeedsRequest" + }, + { + "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.asset_v1.types.ListFeedsResponse", + "shortName": "list_feeds" + }, + "description": "Sample for ListFeeds", + "file": "cloudasset_v1_generated_asset_service_list_feeds_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ListFeeds_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": "cloudasset_v1_generated_asset_service_list_feeds_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.list_saved_queries", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ListSavedQueries", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListSavedQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ListSavedQueriesRequest" + }, + { + "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.asset_v1.services.asset_service.pagers.ListSavedQueriesAsyncPager", + "shortName": "list_saved_queries" + }, + "description": "Sample for ListSavedQueries", + "file": "cloudasset_v1_generated_asset_service_list_saved_queries_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ListSavedQueries_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": "cloudasset_v1_generated_asset_service_list_saved_queries_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.list_saved_queries", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.ListSavedQueries", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListSavedQueries" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.ListSavedQueriesRequest" + }, + { + "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.asset_v1.services.asset_service.pagers.ListSavedQueriesPager", + "shortName": "list_saved_queries" + }, + "description": "Sample for ListSavedQueries", + "file": "cloudasset_v1_generated_asset_service_list_saved_queries_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_ListSavedQueries_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": "cloudasset_v1_generated_asset_service_list_saved_queries_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.query_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.QueryAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "QueryAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.QueryAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.QueryAssetsResponse", + "shortName": "query_assets" + }, + "description": "Sample for QueryAssets", + "file": "cloudasset_v1_generated_asset_service_query_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_QueryAssets_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": "cloudasset_v1_generated_asset_service_query_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.query_assets", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.QueryAssets", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "QueryAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.QueryAssetsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.QueryAssetsResponse", + "shortName": "query_assets" + }, + "description": "Sample for QueryAssets", + "file": "cloudasset_v1_generated_asset_service_query_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_QueryAssets_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": "cloudasset_v1_generated_asset_service_query_assets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.search_all_iam_policies", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.SearchAllIamPolicies", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllIamPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.SearchAllIamPoliciesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager", + "shortName": "search_all_iam_policies" + }, + "description": "Sample for SearchAllIamPolicies", + "file": "cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.search_all_iam_policies", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.SearchAllIamPolicies", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllIamPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.SearchAllIamPoliciesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesPager", + "shortName": "search_all_iam_policies" + }, + "description": "Sample for SearchAllIamPolicies", + "file": "cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.search_all_resources", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.SearchAllResources", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.SearchAllResourcesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "asset_types", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllResourcesAsyncPager", + "shortName": "search_all_resources" + }, + "description": "Sample for SearchAllResources", + "file": "cloudasset_v1_generated_asset_service_search_all_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_SearchAllResources_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": "cloudasset_v1_generated_asset_service_search_all_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.search_all_resources", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.SearchAllResources", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.SearchAllResourcesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "asset_types", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllResourcesPager", + "shortName": "search_all_resources" + }, + "description": "Sample for SearchAllResources", + "file": "cloudasset_v1_generated_asset_service_search_all_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_SearchAllResources_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": "cloudasset_v1_generated_asset_service_search_all_resources_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.update_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.UpdateFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "UpdateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.UpdateFeedRequest" + }, + { + "name": "feed", + "type": "google.cloud.asset_v1.types.Feed" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.Feed", + "shortName": "update_feed" + }, + "description": "Sample for UpdateFeed", + "file": "cloudasset_v1_generated_asset_service_update_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_UpdateFeed_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_update_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.update_feed", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.UpdateFeed", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "UpdateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.UpdateFeedRequest" + }, + { + "name": "feed", + "type": "google.cloud.asset_v1.types.Feed" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1.types.Feed", + "shortName": "update_feed" + }, + "description": "Sample for UpdateFeed", + "file": "cloudasset_v1_generated_asset_service_update_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_UpdateFeed_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1_generated_asset_service_update_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.update_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.UpdateSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "UpdateSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.UpdateSavedQueryRequest" + }, + { + "name": "saved_query", + "type": "google.cloud.asset_v1.types.SavedQuery" + }, + { + "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.asset_v1.types.SavedQuery", + "shortName": "update_saved_query" + }, + "description": "Sample for UpdateSavedQuery", + "file": "cloudasset_v1_generated_asset_service_update_saved_query_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_UpdateSavedQuery_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": "cloudasset_v1_generated_asset_service_update_saved_query_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1.AssetServiceClient.update_saved_query", + "method": { + "fullName": "google.cloud.asset.v1.AssetService.UpdateSavedQuery", + "service": { + "fullName": "google.cloud.asset.v1.AssetService", + "shortName": "AssetService" + }, + "shortName": "UpdateSavedQuery" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1.types.UpdateSavedQueryRequest" + }, + { + "name": "saved_query", + "type": "google.cloud.asset_v1.types.SavedQuery" + }, + { + "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.asset_v1.types.SavedQuery", + "shortName": "update_saved_query" + }, + "description": "Sample for UpdateSavedQuery", + "file": "cloudasset_v1_generated_asset_service_update_saved_query_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1_generated_AssetService_UpdateSavedQuery_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": "cloudasset_v1_generated_asset_service_update_saved_query_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py new file mode 100644 index 00000000..979373d9 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py @@ -0,0 +1,198 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'analyze_iam_policy': ('analysis_query', 'saved_analysis_query', 'execution_timeout', ), + 'analyze_iam_policy_longrunning': ('analysis_query', 'output_config', 'saved_analysis_query', ), + 'analyze_move': ('resource', 'destination_parent', 'view', ), + 'analyze_org_policies': ('scope', 'constraint', 'filter', 'page_size', 'page_token', ), + 'analyze_org_policy_governed_assets': ('scope', 'constraint', 'filter', 'page_size', 'page_token', ), + 'analyze_org_policy_governed_containers': ('scope', 'constraint', 'filter', 'page_size', 'page_token', ), + 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', 'relationship_types', ), + 'batch_get_effective_iam_policies': ('scope', 'names', ), + 'create_feed': ('parent', 'feed_id', 'feed', ), + 'create_saved_query': ('parent', 'saved_query', 'saved_query_id', ), + 'delete_feed': ('name', ), + 'delete_saved_query': ('name', ), + 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', 'relationship_types', ), + 'get_feed': ('name', ), + 'get_saved_query': ('name', ), + 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', 'relationship_types', ), + 'list_feeds': ('parent', ), + 'list_saved_queries': ('parent', 'filter', 'page_size', 'page_token', ), + 'query_assets': ('parent', 'statement', 'job_reference', 'page_size', 'page_token', 'timeout', 'read_time_window', 'read_time', 'output_config', ), + 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', 'asset_types', 'order_by', ), + 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', 'read_mask', ), + 'update_feed': ('feed', 'update_mask', ), + 'update_saved_query': ('saved_query', 'update_mask', ), + } + + 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=assetCallTransformer(), +): + """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 asset 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 00000000..166120b0 --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-asset' + + +description = "Google Cloud Asset API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/asset/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-asset" + +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 00000000..ad3f0fa5 --- /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 00000000..ad3f0fa5 --- /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 00000000..ad3f0fa5 --- /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 00000000..2beecf99 --- /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 00000000..ad3f0fa5 --- /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 00000000..ad3f0fa5 --- /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 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# 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 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# 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 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py new file mode 100644 index 00000000..497b0ed2 --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py @@ -0,0 +1,13601 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.asset_v1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1.services.asset_service import pagers +from google.cloud.asset_v1.services.asset_service import transports +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import expr_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 AssetServiceClient._get_default_mtls_endpoint(None) is None + assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceRestTransport, + ] + assert transport in available_transports + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_asset_service_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", [ + AssetServiceClient, AssetServiceAsyncClient +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), +]) +def test_asset_service_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_asset_service_client_client_options_from_dict(): + with mock.patch('google.cloud.asset_v1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ExportAssetsRequest, + dict, +]) +def test_export_assets(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.export_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ExportAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_assets_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 = AssetServiceClient( + 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.export_assets), + '__call__') as call: + client.export_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ExportAssetsRequest() + +@pytest.mark.asyncio +async def test_export_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.ExportAssetsRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.export_assets), + '__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.export_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ExportAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_assets_async_from_dict(): + await test_export_assets_async(request_type=dict) + + +def test_export_assets_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_assets), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_assets(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_export_assets_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ExportAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_assets(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'] + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_assets_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 = AssetServiceClient( + 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_assets), + '__call__') as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListAssetsRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = asset_service.ListAssetsResponse() + client.list_assets(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_assets_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) + await client.list_assets(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_assets_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + 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_assets_flattened_error(): + client = AssetServiceClient( + 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_assets( + asset_service.ListAssetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_assets_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + 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_assets_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_assets( + asset_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.Asset) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, assets.Asset) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + asset_service.BatchGetAssetsHistoryRequest, + dict, +]) +def test_batch_get_assets_history(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.batch_get_assets_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.BatchGetAssetsHistoryResponse( + ) + response = client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.BatchGetAssetsHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) + + +def test_batch_get_assets_history_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 = AssetServiceClient( + 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.batch_get_assets_history), + '__call__') as call: + client.batch_get_assets_history() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.BatchGetAssetsHistoryRequest() + +@pytest.mark.asyncio +async def test_batch_get_assets_history_async(transport: str = 'grpc_asyncio', request_type=asset_service.BatchGetAssetsHistoryRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.batch_get_assets_history), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetAssetsHistoryResponse( + )) + response = await client.batch_get_assets_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.BatchGetAssetsHistoryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) + + +@pytest.mark.asyncio +async def test_batch_get_assets_history_async_from_dict(): + await test_batch_get_assets_history_async(request_type=dict) + + +def test_batch_get_assets_history_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetAssetsHistoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_assets_history), + '__call__') as call: + call.return_value = asset_service.BatchGetAssetsHistoryResponse() + client.batch_get_assets_history(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_batch_get_assets_history_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetAssetsHistoryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_assets_history), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetAssetsHistoryResponse()) + await client.batch_get_assets_history(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'] + + +@pytest.mark.parametrize("request_type", [ + asset_service.CreateFeedRequest, + dict, +]) +def test_create_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + ) + response = client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +def test_create_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.create_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateFeedRequest() + +@pytest.mark.asyncio +async def test_create_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.CreateFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + )) + response = await client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +@pytest.mark.asyncio +async def test_create_feed_async_from_dict(): + await test_create_feed_async(request_type=dict) + + +def test_create_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + call.return_value = asset_service.Feed() + client.create_feed(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_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + await client.create_feed(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_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_feed( + 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_create_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.CreateFeedRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_create_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_feed( + 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_create_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.CreateFeedRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.GetFeedRequest, + dict, +]) +def test_get_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + ) + response = client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +def test_get_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.get_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetFeedRequest() + +@pytest.mark.asyncio +async def test_get_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.GetFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + )) + response = await client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +@pytest.mark.asyncio +async def test_get_feed_async_from_dict(): + await test_get_feed_async(request_type=dict) + + +def test_get_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + call.return_value = asset_service.Feed() + client.get_feed(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_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + await client.get_feed(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_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_feed( + 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_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.GetFeedRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_feed( + 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_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.GetFeedRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListFeedsRequest, + dict, +]) +def test_list_feeds(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse( + ) + response = client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListFeedsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_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 = AssetServiceClient( + 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_feeds), + '__call__') as call: + client.list_feeds() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListFeedsRequest() + +@pytest.mark.asyncio +async def test_list_feeds_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListFeedsRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse( + )) + response = await client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListFeedsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +@pytest.mark.asyncio +async def test_list_feeds_async_from_dict(): + await test_list_feeds_async(request_type=dict) + + +def test_list_feeds_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + call.return_value = asset_service.ListFeedsResponse() + client.list_feeds(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_feeds_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) + await client.list_feeds(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_feeds_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_feeds( + 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_feeds_flattened_error(): + client = AssetServiceClient( + 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_feeds( + asset_service.ListFeedsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_feeds_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_feeds( + 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_feeds_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feeds( + asset_service.ListFeedsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.UpdateFeedRequest, + dict, +]) +def test_update_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + ) + response = client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +def test_update_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.update_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateFeedRequest() + +@pytest.mark.asyncio +async def test_update_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.UpdateFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + )) + response = await client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +@pytest.mark.asyncio +async def test_update_feed_async_from_dict(): + await test_update_feed_async(request_type=dict) + + +def test_update_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + + request.feed.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + call.return_value = asset_service.Feed() + client.update_feed(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', + 'feed.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + + request.feed.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + await client.update_feed(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', + 'feed.name=name_value', + ) in kw['metadata'] + + +def test_update_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_feed( + feed=asset_service.Feed(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].feed + mock_val = asset_service.Feed(name='name_value') + assert arg == mock_val + + +def test_update_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_feed( + feed=asset_service.Feed(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].feed + mock_val = asset_service.Feed(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.DeleteFeedRequest, + dict, +]) +def test_delete_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteFeedRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.delete_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteFeedRequest() + +@pytest.mark.asyncio +async def test_delete_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.DeleteFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteFeedRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_feed_async_from_dict(): + await test_delete_feed_async(request_type=dict) + + +def test_delete_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__call__') as call: + call.return_value = None + client.delete_feed(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_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_feed(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_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__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_feed( + 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_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.DeleteFeedRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__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_feed( + 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_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.DeleteFeedRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.SearchAllResourcesRequest, + dict, +]) +def test_search_all_resources(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_resources_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 = AssetServiceClient( + 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.search_all_resources), + '__call__') as call: + client.search_all_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllResourcesRequest() + +@pytest.mark.asyncio +async def test_search_all_resources_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllResourcesRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_all_resources_async_from_dict(): + await test_search_all_resources_async(request_type=dict) + + +def test_search_all_resources_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + call.return_value = asset_service.SearchAllResourcesResponse() + client.search_all_resources(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_all_resources_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) + await client.search_all_resources(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', + 'scope=scope_value', + ) in kw['metadata'] + + +def test_search_all_resources_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_resources( + scope='scope_value', + query='query_value', + asset_types=['asset_types_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + arg = args[0].asset_types + mock_val = ['asset_types_value'] + assert arg == mock_val + + +def test_search_all_resources_flattened_error(): + client = AssetServiceClient( + 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.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_resources( + scope='scope_value', + query='query_value', + asset_types=['asset_types_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + arg = args[0].asset_types + mock_val = ['asset_types_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_error_async(): + client = AssetServiceAsyncClient( + 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.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + + +def test_search_all_resources_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('scope', ''), + )), + ) + pager = client.search_all_resources(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.ResourceSearchResult) + for i in results) +def test_search_all_resources_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_all_resources(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_search_all_resources_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_all_resources(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, assets.ResourceSearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_resources_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_all_resources(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + asset_service.SearchAllIamPoliciesRequest, + dict, +]) +def test_search_all_iam_policies(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_iam_policies_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 = AssetServiceClient( + 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.search_all_iam_policies), + '__call__') as call: + client.search_all_iam_policies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllIamPoliciesRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_from_dict(): + await test_search_all_iam_policies_async(request_type=dict) + + +def test_search_all_iam_policies_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + call.return_value = asset_service.SearchAllIamPoliciesResponse() + client.search_all_iam_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) + await client.search_all_iam_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +def test_search_all_iam_policies_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_iam_policies( + scope='scope_value', + query='query_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + + +def test_search_all_iam_policies_flattened_error(): + client = AssetServiceClient( + 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.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope='scope_value', + query='query_value', + ) + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_iam_policies( + scope='scope_value', + query='query_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_error_async(): + client = AssetServiceAsyncClient( + 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.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope='scope_value', + query='query_value', + ) + + +def test_search_all_iam_policies_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_iam_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('scope', ''), + )), + ) + pager = client.search_all_iam_policies(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) + for i in results) +def test_search_all_iam_policies_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_iam_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_all_iam_policies(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_search_all_iam_policies_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_all_iam_policies(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, assets.IamPolicySearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_all_iam_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeIamPolicyRequest, + dict, +]) +def test_analyze_iam_policy(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeIamPolicyResponse( + fully_explored=True, + ) + response = client.analyze_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] == asset_service.AnalyzeIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) + assert response.fully_explored is True + + +def test_analyze_iam_policy_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 = AssetServiceClient( + 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.analyze_iam_policy), + '__call__') as call: + client.analyze_iam_policy() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeIamPolicyRequest() + +@pytest.mark.asyncio +async def test_analyze_iam_policy_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeIamPolicyRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_iam_policy), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeIamPolicyResponse( + fully_explored=True, + )) + response = await client.analyze_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] == asset_service.AnalyzeIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) + assert response.fully_explored is True + + +@pytest.mark.asyncio +async def test_analyze_iam_policy_async_from_dict(): + await test_analyze_iam_policy_async(request_type=dict) + + +def test_analyze_iam_policy_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeIamPolicyRequest() + + request.analysis_query.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_iam_policy), + '__call__') as call: + call.return_value = asset_service.AnalyzeIamPolicyResponse() + client.analyze_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', + 'analysis_query.scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_analyze_iam_policy_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeIamPolicyRequest() + + request.analysis_query.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_iam_policy), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeIamPolicyResponse()) + await client.analyze_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', + 'analysis_query.scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeIamPolicyLongrunningRequest, + dict, +]) +def test_analyze_iam_policy_longrunning(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_iam_policy_longrunning), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.analyze_iam_policy_longrunning(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeIamPolicyLongrunningRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_analyze_iam_policy_longrunning_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 = AssetServiceClient( + 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.analyze_iam_policy_longrunning), + '__call__') as call: + client.analyze_iam_policy_longrunning() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeIamPolicyLongrunningRequest() + +@pytest.mark.asyncio +async def test_analyze_iam_policy_longrunning_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_iam_policy_longrunning), + '__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.analyze_iam_policy_longrunning(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeIamPolicyLongrunningRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_analyze_iam_policy_longrunning_async_from_dict(): + await test_analyze_iam_policy_longrunning_async(request_type=dict) + + +def test_analyze_iam_policy_longrunning_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeIamPolicyLongrunningRequest() + + request.analysis_query.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_iam_policy_longrunning), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.analyze_iam_policy_longrunning(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', + 'analysis_query.scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_analyze_iam_policy_longrunning_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeIamPolicyLongrunningRequest() + + request.analysis_query.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_iam_policy_longrunning), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.analyze_iam_policy_longrunning(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', + 'analysis_query.scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeMoveRequest, + dict, +]) +def test_analyze_move(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_move), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeMoveResponse( + ) + response = client.analyze_move(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeMoveRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeMoveResponse) + + +def test_analyze_move_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 = AssetServiceClient( + 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.analyze_move), + '__call__') as call: + client.analyze_move() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeMoveRequest() + +@pytest.mark.asyncio +async def test_analyze_move_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeMoveRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_move), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeMoveResponse( + )) + response = await client.analyze_move(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeMoveRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeMoveResponse) + + +@pytest.mark.asyncio +async def test_analyze_move_async_from_dict(): + await test_analyze_move_async(request_type=dict) + + +def test_analyze_move_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeMoveRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_move), + '__call__') as call: + call.return_value = asset_service.AnalyzeMoveResponse() + client.analyze_move(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_analyze_move_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeMoveRequest() + + request.resource = 'resource_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_move), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeMoveResponse()) + await client.analyze_move(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'] + + +@pytest.mark.parametrize("request_type", [ + asset_service.QueryAssetsRequest, + dict, +]) +def test_query_assets(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.query_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.QueryAssetsResponse( + job_reference='job_reference_value', + done=True, + ) + response = client.query_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.QueryAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.QueryAssetsResponse) + assert response.job_reference == 'job_reference_value' + assert response.done is True + + +def test_query_assets_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 = AssetServiceClient( + 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.query_assets), + '__call__') as call: + client.query_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.QueryAssetsRequest() + +@pytest.mark.asyncio +async def test_query_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.QueryAssetsRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.query_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.QueryAssetsResponse( + job_reference='job_reference_value', + done=True, + )) + response = await client.query_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.QueryAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.QueryAssetsResponse) + assert response.job_reference == 'job_reference_value' + assert response.done is True + + +@pytest.mark.asyncio +async def test_query_assets_async_from_dict(): + await test_query_assets_async(request_type=dict) + + +def test_query_assets_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.QueryAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_assets), + '__call__') as call: + call.return_value = asset_service.QueryAssetsResponse() + client.query_assets(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_query_assets_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.QueryAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.query_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.QueryAssetsResponse()) + await client.query_assets(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'] + + +@pytest.mark.parametrize("request_type", [ + asset_service.CreateSavedQueryRequest, + dict, +]) +def test_create_saved_query(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + ) + response = client.create_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +def test_create_saved_query_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 = AssetServiceClient( + 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_saved_query), + '__call__') as call: + client.create_saved_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateSavedQueryRequest() + +@pytest.mark.asyncio +async def test_create_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.CreateSavedQueryRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + )) + response = await client.create_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +@pytest.mark.asyncio +async def test_create_saved_query_async_from_dict(): + await test_create_saved_query_async(request_type=dict) + + +def test_create_saved_query_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateSavedQueryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_saved_query), + '__call__') as call: + call.return_value = asset_service.SavedQuery() + client.create_saved_query(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_saved_query_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateSavedQueryRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_saved_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) + await client.create_saved_query(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_saved_query_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_saved_query( + parent='parent_value', + saved_query=asset_service.SavedQuery(name='name_value'), + saved_query_id='saved_query_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].saved_query + mock_val = asset_service.SavedQuery(name='name_value') + assert arg == mock_val + arg = args[0].saved_query_id + mock_val = 'saved_query_id_value' + assert arg == mock_val + + +def test_create_saved_query_flattened_error(): + client = AssetServiceClient( + 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_saved_query( + asset_service.CreateSavedQueryRequest(), + parent='parent_value', + saved_query=asset_service.SavedQuery(name='name_value'), + saved_query_id='saved_query_id_value', + ) + +@pytest.mark.asyncio +async def test_create_saved_query_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_saved_query( + parent='parent_value', + saved_query=asset_service.SavedQuery(name='name_value'), + saved_query_id='saved_query_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].saved_query + mock_val = asset_service.SavedQuery(name='name_value') + assert arg == mock_val + arg = args[0].saved_query_id + mock_val = 'saved_query_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_saved_query_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_saved_query( + asset_service.CreateSavedQueryRequest(), + parent='parent_value', + saved_query=asset_service.SavedQuery(name='name_value'), + saved_query_id='saved_query_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.GetSavedQueryRequest, + dict, +]) +def test_get_saved_query(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + ) + response = client.get_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +def test_get_saved_query_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 = AssetServiceClient( + 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_saved_query), + '__call__') as call: + client.get_saved_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetSavedQueryRequest() + +@pytest.mark.asyncio +async def test_get_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.GetSavedQueryRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + )) + response = await client.get_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +@pytest.mark.asyncio +async def test_get_saved_query_async_from_dict(): + await test_get_saved_query_async(request_type=dict) + + +def test_get_saved_query_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetSavedQueryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_saved_query), + '__call__') as call: + call.return_value = asset_service.SavedQuery() + client.get_saved_query(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_saved_query_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetSavedQueryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_saved_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) + await client.get_saved_query(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_saved_query_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_saved_query( + 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_saved_query_flattened_error(): + client = AssetServiceClient( + 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_saved_query( + asset_service.GetSavedQueryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_saved_query_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_saved_query( + 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_saved_query_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_saved_query( + asset_service.GetSavedQueryRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListSavedQueriesRequest, + dict, +]) +def test_list_saved_queries(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_queries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListSavedQueriesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_saved_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListSavedQueriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSavedQueriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_saved_queries_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 = AssetServiceClient( + 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_saved_queries), + '__call__') as call: + client.list_saved_queries() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListSavedQueriesRequest() + +@pytest.mark.asyncio +async def test_list_saved_queries_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListSavedQueriesRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_queries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListSavedQueriesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_saved_queries(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListSavedQueriesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSavedQueriesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_saved_queries_async_from_dict(): + await test_list_saved_queries_async(request_type=dict) + + +def test_list_saved_queries_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListSavedQueriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_saved_queries), + '__call__') as call: + call.return_value = asset_service.ListSavedQueriesResponse() + client.list_saved_queries(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_saved_queries_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListSavedQueriesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_saved_queries), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListSavedQueriesResponse()) + await client.list_saved_queries(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_saved_queries_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_saved_queries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListSavedQueriesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_saved_queries( + 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_saved_queries_flattened_error(): + client = AssetServiceClient( + 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_saved_queries( + asset_service.ListSavedQueriesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_saved_queries_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_saved_queries), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListSavedQueriesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListSavedQueriesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_saved_queries( + 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_saved_queries_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_saved_queries( + asset_service.ListSavedQueriesRequest(), + parent='parent_value', + ) + + +def test_list_saved_queries_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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_saved_queries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + next_page_token='abc', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[], + next_page_token='def', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + ], + next_page_token='ghi', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_saved_queries(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.SavedQuery) + for i in results) +def test_list_saved_queries_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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_saved_queries), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + next_page_token='abc', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[], + next_page_token='def', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + ], + next_page_token='ghi', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + ), + RuntimeError, + ) + pages = list(client.list_saved_queries(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_saved_queries_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_saved_queries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + next_page_token='abc', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[], + next_page_token='def', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + ], + next_page_token='ghi', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_saved_queries(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, asset_service.SavedQuery) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_saved_queries_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_saved_queries), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + next_page_token='abc', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[], + next_page_token='def', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + ], + next_page_token='ghi', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_saved_queries(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + asset_service.UpdateSavedQueryRequest, + dict, +]) +def test_update_saved_query(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + ) + response = client.update_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +def test_update_saved_query_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 = AssetServiceClient( + 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_saved_query), + '__call__') as call: + client.update_saved_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateSavedQueryRequest() + +@pytest.mark.asyncio +async def test_update_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.UpdateSavedQueryRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + )) + response = await client.update_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +@pytest.mark.asyncio +async def test_update_saved_query_async_from_dict(): + await test_update_saved_query_async(request_type=dict) + + +def test_update_saved_query_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateSavedQueryRequest() + + request.saved_query.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_saved_query), + '__call__') as call: + call.return_value = asset_service.SavedQuery() + client.update_saved_query(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', + 'saved_query.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_saved_query_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateSavedQueryRequest() + + request.saved_query.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_saved_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) + await client.update_saved_query(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', + 'saved_query.name=name_value', + ) in kw['metadata'] + + +def test_update_saved_query_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_saved_query( + saved_query=asset_service.SavedQuery(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].saved_query + mock_val = asset_service.SavedQuery(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_saved_query_flattened_error(): + client = AssetServiceClient( + 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_saved_query( + asset_service.UpdateSavedQueryRequest(), + saved_query=asset_service.SavedQuery(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_saved_query_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SavedQuery() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_saved_query( + saved_query=asset_service.SavedQuery(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].saved_query + mock_val = asset_service.SavedQuery(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_saved_query_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_saved_query( + asset_service.UpdateSavedQueryRequest(), + saved_query=asset_service.SavedQuery(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.DeleteSavedQueryRequest, + dict, +]) +def test_delete_saved_query(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_saved_query_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 = AssetServiceClient( + 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_saved_query), + '__call__') as call: + client.delete_saved_query() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteSavedQueryRequest() + +@pytest.mark.asyncio +async def test_delete_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.DeleteSavedQueryRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_saved_query), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_saved_query(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteSavedQueryRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_saved_query_async_from_dict(): + await test_delete_saved_query_async(request_type=dict) + + +def test_delete_saved_query_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteSavedQueryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_saved_query), + '__call__') as call: + call.return_value = None + client.delete_saved_query(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_saved_query_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteSavedQueryRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_saved_query), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_saved_query(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_saved_query_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_saved_query), + '__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_saved_query( + 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_saved_query_flattened_error(): + client = AssetServiceClient( + 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_saved_query( + asset_service.DeleteSavedQueryRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_saved_query_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_saved_query), + '__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_saved_query( + 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_saved_query_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_saved_query( + asset_service.DeleteSavedQueryRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.BatchGetEffectiveIamPoliciesRequest, + dict, +]) +def test_batch_get_effective_iam_policies(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.batch_get_effective_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.BatchGetEffectiveIamPoliciesResponse( + ) + response = client.batch_get_effective_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.BatchGetEffectiveIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetEffectiveIamPoliciesResponse) + + +def test_batch_get_effective_iam_policies_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 = AssetServiceClient( + 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.batch_get_effective_iam_policies), + '__call__') as call: + client.batch_get_effective_iam_policies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.BatchGetEffectiveIamPoliciesRequest() + +@pytest.mark.asyncio +async def test_batch_get_effective_iam_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.BatchGetEffectiveIamPoliciesRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.batch_get_effective_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetEffectiveIamPoliciesResponse( + )) + response = await client.batch_get_effective_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.BatchGetEffectiveIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetEffectiveIamPoliciesResponse) + + +@pytest.mark.asyncio +async def test_batch_get_effective_iam_policies_async_from_dict(): + await test_batch_get_effective_iam_policies_async(request_type=dict) + + +def test_batch_get_effective_iam_policies_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetEffectiveIamPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_effective_iam_policies), + '__call__') as call: + call.return_value = asset_service.BatchGetEffectiveIamPoliciesResponse() + client.batch_get_effective_iam_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_batch_get_effective_iam_policies_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.BatchGetEffectiveIamPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_get_effective_iam_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetEffectiveIamPoliciesResponse()) + await client.batch_get_effective_iam_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeOrgPoliciesRequest, + dict, +]) +def test_analyze_org_policies(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_org_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.analyze_org_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_analyze_org_policies_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 = AssetServiceClient( + 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.analyze_org_policies), + '__call__') as call: + client.analyze_org_policies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPoliciesRequest() + +@pytest.mark.asyncio +async def test_analyze_org_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeOrgPoliciesRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_org_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.analyze_org_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_analyze_org_policies_async_from_dict(): + await test_analyze_org_policies_async(request_type=dict) + + +def test_analyze_org_policies_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeOrgPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policies), + '__call__') as call: + call.return_value = asset_service.AnalyzeOrgPoliciesResponse() + client.analyze_org_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_analyze_org_policies_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeOrgPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPoliciesResponse()) + await client.analyze_org_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +def test_analyze_org_policies_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.analyze_org_policies( + scope='scope_value', + constraint='constraint_value', + filter='filter_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].constraint + mock_val = 'constraint_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_analyze_org_policies_flattened_error(): + client = AssetServiceClient( + 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.analyze_org_policies( + asset_service.AnalyzeOrgPoliciesRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_analyze_org_policies_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.analyze_org_policies( + scope='scope_value', + constraint='constraint_value', + filter='filter_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].constraint + mock_val = 'constraint_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_analyze_org_policies_flattened_error_async(): + client = AssetServiceAsyncClient( + 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.analyze_org_policies( + asset_service.AnalyzeOrgPoliciesRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + + +def test_analyze_org_policies_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.analyze_org_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('scope', ''), + )), + ) + pager = client.analyze_org_policies(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult) + for i in results) +def test_analyze_org_policies_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.analyze_org_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + ), + RuntimeError, + ) + pages = list(client.analyze_org_policies(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_analyze_org_policies_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.analyze_org_policies(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, asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_analyze_org_policies_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.analyze_org_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeOrgPolicyGovernedContainersRequest, + dict, +]) +def test_analyze_org_policy_governed_containers(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_org_policy_governed_containers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + next_page_token='next_page_token_value', + ) + response = client.analyze_org_policy_governed_containers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPolicyGovernedContainersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedContainersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_analyze_org_policy_governed_containers_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 = AssetServiceClient( + 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.analyze_org_policy_governed_containers), + '__call__') as call: + client.analyze_org_policy_governed_containers() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPolicyGovernedContainersRequest() + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_containers_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_org_policy_governed_containers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + next_page_token='next_page_token_value', + )) + response = await client.analyze_org_policy_governed_containers(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPolicyGovernedContainersRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_containers_async_from_dict(): + await test_analyze_org_policy_governed_containers_async(request_type=dict) + + +def test_analyze_org_policy_governed_containers_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_containers), + '__call__') as call: + call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() + client.analyze_org_policy_governed_containers(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_containers_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_containers), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedContainersResponse()) + await client.analyze_org_policy_governed_containers(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', + 'scope=scope_value', + ) in kw['metadata'] + + +def test_analyze_org_policy_governed_containers_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_containers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.analyze_org_policy_governed_containers( + scope='scope_value', + constraint='constraint_value', + filter='filter_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].constraint + mock_val = 'constraint_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_analyze_org_policy_governed_containers_flattened_error(): + client = AssetServiceClient( + 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.analyze_org_policy_governed_containers( + asset_service.AnalyzeOrgPolicyGovernedContainersRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_containers_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_containers), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedContainersResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.analyze_org_policy_governed_containers( + scope='scope_value', + constraint='constraint_value', + filter='filter_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].constraint + mock_val = 'constraint_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_containers_flattened_error_async(): + client = AssetServiceAsyncClient( + 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.analyze_org_policy_governed_containers( + asset_service.AnalyzeOrgPolicyGovernedContainersRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + + +def test_analyze_org_policy_governed_containers_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.analyze_org_policy_governed_containers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('scope', ''), + )), + ) + pager = client.analyze_org_policy_governed_containers(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer) + for i in results) +def test_analyze_org_policy_governed_containers_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.analyze_org_policy_governed_containers), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + ), + RuntimeError, + ) + pages = list(client.analyze_org_policy_governed_containers(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_analyze_org_policy_governed_containers_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_containers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + ), + RuntimeError, + ) + async_pager = await client.analyze_org_policy_governed_containers(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, asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer) + for i in responses) + + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_containers_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_containers), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.analyze_org_policy_governed_containers(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, + dict, +]) +def test_analyze_org_policy_governed_assets(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_org_policy_governed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.analyze_org_policy_governed_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_analyze_org_policy_governed_assets_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 = AssetServiceClient( + 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.analyze_org_policy_governed_assets), + '__call__') as call: + client.analyze_org_policy_governed_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.analyze_org_policy_governed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.analyze_org_policy_governed_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_assets_async_from_dict(): + await test_analyze_org_policy_governed_assets_async(request_type=dict) + + +def test_analyze_org_policy_governed_assets_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_assets), + '__call__') as call: + call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() + client.analyze_org_policy_governed_assets(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_assets_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse()) + await client.analyze_org_policy_governed_assets(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', + 'scope=scope_value', + ) in kw['metadata'] + + +def test_analyze_org_policy_governed_assets_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.analyze_org_policy_governed_assets( + scope='scope_value', + constraint='constraint_value', + filter='filter_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].constraint + mock_val = 'constraint_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + + +def test_analyze_org_policy_governed_assets_flattened_error(): + client = AssetServiceClient( + 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.analyze_org_policy_governed_assets( + asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_assets_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.analyze_org_policy_governed_assets( + scope='scope_value', + constraint='constraint_value', + filter='filter_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].constraint + mock_val = 'constraint_value' + assert arg == mock_val + arg = args[0].filter + mock_val = 'filter_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_assets_flattened_error_async(): + client = AssetServiceAsyncClient( + 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.analyze_org_policy_governed_assets( + asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + + +def test_analyze_org_policy_governed_assets_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.analyze_org_policy_governed_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('scope', ''), + )), + ) + pager = client.analyze_org_policy_governed_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset) + for i in results) +def test_analyze_org_policy_governed_assets_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.analyze_org_policy_governed_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + ), + RuntimeError, + ) + pages = list(client.analyze_org_policy_governed_assets(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_analyze_org_policy_governed_assets_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + ), + RuntimeError, + ) + async_pager = await client.analyze_org_policy_governed_assets(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, asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset) + for i in responses) + + +@pytest.mark.asyncio +async def test_analyze_org_policy_governed_assets_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.analyze_org_policy_governed_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.analyze_org_policy_governed_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + asset_service.ExportAssetsRequest, + dict, +]) +def test_export_assets_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # 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.export_assets(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_export_assets_rest_required_fields(request_type=asset_service.ExportAssetsRequest): + transport_class = transports.AssetServiceRestTransport + + 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()).export_assets._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()).export_assets._get_unset_required_fields(jsonified_request) + 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 = AssetServiceClient( + 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.export_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_export_assets_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.export_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "outputConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_assets_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_export_assets") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_export_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.ExportAssetsRequest.pb(asset_service.ExportAssetsRequest()) + 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 = asset_service.ExportAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.export_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_export_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.ExportAssetsRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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.export_assets(request) + + +def test_export_assets_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_assets_rest_required_fields(request_type=asset_service.ListAssetsRequest): + transport_class = transports.AssetServiceRestTransport + + 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_assets._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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_types", "content_type", "page_size", "page_token", "read_time", "relationship_types", )) + 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.ListAssetsResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetTypes", "contentType", "pageSize", "pageToken", "readTime", "relationshipTypes", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.ListAssetsRequest.pb(asset_service.ListAssetsRequest()) + 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 = asset_service.ListAssetsResponse.to_json(asset_service.ListAssetsResponse()) + + request = asset_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListAssetsRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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_assets(request) + + +def test_list_assets_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.ListAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/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 + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_assets(**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=*/*}/assets" % client.transport._host, args[1]) + + +def test_list_assets_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_assets( + asset_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.ListAssetsResponse.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': 'sample1/sample2'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.Asset) + for i in results) + + pages = list(client.list_assets(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", [ + asset_service.BatchGetAssetsHistoryRequest, + dict, +]) +def test_batch_get_assets_history_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.BatchGetAssetsHistoryResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.BatchGetAssetsHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_get_assets_history(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) + + +def test_batch_get_assets_history_rest_required_fields(request_type=asset_service.BatchGetAssetsHistoryRequest): + transport_class = transports.AssetServiceRestTransport + + 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()).batch_get_assets_history._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()).batch_get_assets_history._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_names", "content_type", "read_time_window", "relationship_types", )) + 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.BatchGetAssetsHistoryResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.BatchGetAssetsHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_get_assets_history(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_get_assets_history_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_get_assets_history._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetNames", "contentType", "readTimeWindow", "relationshipTypes", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_get_assets_history_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_batch_get_assets_history") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_batch_get_assets_history") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.BatchGetAssetsHistoryRequest.pb(asset_service.BatchGetAssetsHistoryRequest()) + 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 = asset_service.BatchGetAssetsHistoryResponse.to_json(asset_service.BatchGetAssetsHistoryResponse()) + + request = asset_service.BatchGetAssetsHistoryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.BatchGetAssetsHistoryResponse() + + client.batch_get_assets_history(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_get_assets_history_rest_bad_request(transport: str = 'rest', request_type=asset_service.BatchGetAssetsHistoryRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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.batch_get_assets_history(request) + + +def test_batch_get_assets_history_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.CreateFeedRequest, + dict, +]) +def test_create_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_feed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +def test_create_feed_rest_required_fields(request_type=asset_service.CreateFeedRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["feed_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()).create_feed._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["feedId"] = 'feed_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_feed._get_unset_required_fields(jsonified_request) + 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 "feedId" in jsonified_request + assert jsonified_request["feedId"] == 'feed_id_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.Feed() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "feedId", "feed", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_create_feed") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_create_feed") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.CreateFeedRequest.pb(asset_service.CreateFeedRequest()) + 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 = asset_service.Feed.to_json(asset_service.Feed()) + + request = asset_service.CreateFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.Feed() + + client.create_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.CreateFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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.create_feed(request) + + +def test_create_feed_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.Feed() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/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 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_feed(**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=*/*}/feeds" % client.transport._host, args[1]) + + +def test_create_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.CreateFeedRequest(), + parent='parent_value', + ) + + +def test_create_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.GetFeedRequest, + dict, +]) +def test_get_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_feed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +def test_get_feed_rest_required_fields(request_type=asset_service.GetFeedRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feed._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_feed._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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.Feed() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_get_feed") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_get_feed") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.GetFeedRequest.pb(asset_service.GetFeedRequest()) + 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 = asset_service.Feed.to_json(asset_service.Feed()) + + request = asset_service.GetFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.Feed() + + client.get_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.GetFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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_feed(request) + + +def test_get_feed_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.Feed() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'sample1/sample2/feeds/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 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_feed(**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=*/*/feeds/*}" % client.transport._host, args[1]) + + +def test_get_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.GetFeedRequest(), + name='name_value', + ) + + +def test_get_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListFeedsRequest, + dict, +]) +def test_list_feeds_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.ListFeedsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_feeds(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_rest_required_fields(request_type=asset_service.ListFeedsRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feeds._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_feeds._get_unset_required_fields(jsonified_request) + 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.ListFeedsResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_feeds(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_feeds_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_feeds._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_feeds_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_feeds") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_feeds") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.ListFeedsRequest.pb(asset_service.ListFeedsRequest()) + 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 = asset_service.ListFeedsResponse.to_json(asset_service.ListFeedsResponse()) + + request = asset_service.ListFeedsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.ListFeedsResponse() + + client.list_feeds(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_feeds_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListFeedsRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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_feeds(request) + + +def test_list_feeds_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.ListFeedsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/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 + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_feeds(**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=*/*}/feeds" % client.transport._host, args[1]) + + +def test_list_feeds_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feeds( + asset_service.ListFeedsRequest(), + parent='parent_value', + ) + + +def test_list_feeds_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.UpdateFeedRequest, + dict, +]) +def test_update_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'feed': {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + relationship_types=['relationship_types_value'], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_feed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + assert response.relationship_types == ['relationship_types_value'] + + +def test_update_feed_rest_required_fields(request_type=asset_service.UpdateFeedRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feed._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_feed._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.Feed() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("feed", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_update_feed") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_update_feed") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.UpdateFeedRequest.pb(asset_service.UpdateFeedRequest()) + 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 = asset_service.Feed.to_json(asset_service.Feed()) + + request = asset_service.UpdateFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.Feed() + + client.update_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.UpdateFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'feed': {'name': 'sample1/sample2/feeds/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.update_feed(request) + + +def test_update_feed_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.Feed() + + # get arguments that satisfy an http rule for this method + sample_request = {'feed': {'name': 'sample1/sample2/feeds/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + feed=asset_service.Feed(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_feed(**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/{feed.name=*/*/feeds/*}" % client.transport._host, args[1]) + + +def test_update_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name='name_value'), + ) + + +def test_update_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.DeleteFeedRequest, + dict, +]) +def test_delete_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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_feed(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_rest_required_fields(request_type=asset_service.DeleteFeedRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feed._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_feed._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 = AssetServiceClient( + 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_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "pre_delete_feed") as pre: + pre.assert_not_called() + pb_message = asset_service.DeleteFeedRequest.pb(asset_service.DeleteFeedRequest()) + 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 = asset_service.DeleteFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.DeleteFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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_feed(request) + + +def test_delete_feed_rest_flattened(): + client = AssetServiceClient( + 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': 'sample1/sample2/feeds/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_feed(**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=*/*/feeds/*}" % client.transport._host, args[1]) + + +def test_delete_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.DeleteFeedRequest(), + name='name_value', + ) + + +def test_delete_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.SearchAllResourcesRequest, + dict, +]) +def test_search_all_resources_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.SearchAllResourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_all_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_resources_rest_required_fields(request_type=asset_service.SearchAllResourcesRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + 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()).search_all_resources._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scope"] = 'scope_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_resources._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_types", "order_by", "page_size", "page_token", "query", "read_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.SearchAllResourcesResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_all_resources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_all_resources_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_all_resources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetTypes", "orderBy", "pageSize", "pageToken", "query", "readMask", )) & set(("scope", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_all_resources_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_resources") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_resources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.SearchAllResourcesRequest.pb(asset_service.SearchAllResourcesRequest()) + 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 = asset_service.SearchAllResourcesResponse.to_json(asset_service.SearchAllResourcesResponse()) + + request = asset_service.SearchAllResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.SearchAllResourcesResponse() + + client.search_all_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_all_resources_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllResourcesRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.search_all_resources(request) + + +def test_search_all_resources_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.SearchAllResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'scope': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.search_all_resources(**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/{scope=*/*}:searchAllResources" % client.transport._host, args[1]) + + +def test_search_all_resources_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + + +def test_search_all_resources_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.ResourceSearchResult(), + assets.ResourceSearchResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.SearchAllResourcesResponse.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 = {'scope': 'sample1/sample2'} + + pager = client.search_all_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.ResourceSearchResult) + for i in results) + + pages = list(client.search_all_resources(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", [ + asset_service.SearchAllIamPoliciesRequest, + dict, +]) +def test_search_all_iam_policies_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.SearchAllIamPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_all_iam_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_iam_policies_rest_required_fields(request_type=asset_service.SearchAllIamPoliciesRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + 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()).search_all_iam_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scope"] = 'scope_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_iam_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_types", "order_by", "page_size", "page_token", "query", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.SearchAllIamPoliciesResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_all_iam_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_all_iam_policies_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_all_iam_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetTypes", "orderBy", "pageSize", "pageToken", "query", )) & set(("scope", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_all_iam_policies_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_iam_policies") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_iam_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.SearchAllIamPoliciesRequest.pb(asset_service.SearchAllIamPoliciesRequest()) + 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 = asset_service.SearchAllIamPoliciesResponse.to_json(asset_service.SearchAllIamPoliciesResponse()) + + request = asset_service.SearchAllIamPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.SearchAllIamPoliciesResponse() + + client.search_all_iam_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_all_iam_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllIamPoliciesRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.search_all_iam_policies(request) + + +def test_search_all_iam_policies_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.SearchAllIamPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'scope': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + scope='scope_value', + query='query_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.search_all_iam_policies(**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/{scope=*/*}:searchAllIamPolicies" % client.transport._host, args[1]) + + +def test_search_all_iam_policies_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope='scope_value', + query='query_value', + ) + + +def test_search_all_iam_policies_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.SearchAllIamPoliciesResponse.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 = {'scope': 'sample1/sample2'} + + pager = client.search_all_iam_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) + for i in results) + + pages = list(client.search_all_iam_policies(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", [ + asset_service.AnalyzeIamPolicyRequest, + dict, +]) +def test_analyze_iam_policy_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'analysis_query': {'scope': 'sample1/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 = asset_service.AnalyzeIamPolicyResponse( + fully_explored=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.analyze_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) + assert response.fully_explored is True + + +def test_analyze_iam_policy_rest_required_fields(request_type=asset_service.AnalyzeIamPolicyRequest): + transport_class = transports.AssetServiceRestTransport + + 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()).analyze_iam_policy._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()).analyze_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("analysis_query", "execution_timeout", "saved_analysis_query", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.AnalyzeIamPolicyResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.analyze_iam_policy(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_iam_policy_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("analysisQuery", "executionTimeout", "savedAnalysisQuery", )) & set(("analysisQuery", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_iam_policy_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_iam_policy") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_iam_policy") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.AnalyzeIamPolicyRequest.pb(asset_service.AnalyzeIamPolicyRequest()) + 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 = asset_service.AnalyzeIamPolicyResponse.to_json(asset_service.AnalyzeIamPolicyResponse()) + + request = asset_service.AnalyzeIamPolicyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.AnalyzeIamPolicyResponse() + + client.analyze_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_iam_policy_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeIamPolicyRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'analysis_query': {'scope': 'sample1/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.analyze_iam_policy(request) + + +def test_analyze_iam_policy_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeIamPolicyLongrunningRequest, + dict, +]) +def test_analyze_iam_policy_longrunning_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'analysis_query': {'scope': 'sample1/sample2'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # 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.analyze_iam_policy_longrunning(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_analyze_iam_policy_longrunning_rest_required_fields(request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): + transport_class = transports.AssetServiceRestTransport + + 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()).analyze_iam_policy_longrunning._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()).analyze_iam_policy_longrunning._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AssetServiceClient( + 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.analyze_iam_policy_longrunning(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_iam_policy_longrunning_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_iam_policy_longrunning._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("analysisQuery", "outputConfig", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_iam_policy_longrunning_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_iam_policy_longrunning") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_iam_policy_longrunning") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.AnalyzeIamPolicyLongrunningRequest.pb(asset_service.AnalyzeIamPolicyLongrunningRequest()) + 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 = asset_service.AnalyzeIamPolicyLongrunningRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.analyze_iam_policy_longrunning(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_iam_policy_longrunning_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'analysis_query': {'scope': 'sample1/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.analyze_iam_policy_longrunning(request) + + +def test_analyze_iam_policy_longrunning_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeMoveRequest, + dict, +]) +def test_analyze_move_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'sample1/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 = asset_service.AnalyzeMoveResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeMoveResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.analyze_move(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.AnalyzeMoveResponse) + + +def test_analyze_move_rest_required_fields(request_type=asset_service.AnalyzeMoveRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["destination_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 + assert "destinationParent" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_move._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "destinationParent" in jsonified_request + assert jsonified_request["destinationParent"] == request_init["destination_parent"] + + jsonified_request["resource"] = 'resource_value' + jsonified_request["destinationParent"] = 'destination_parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_move._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("destination_parent", "view", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == 'resource_value' + assert "destinationParent" in jsonified_request + assert jsonified_request["destinationParent"] == 'destination_parent_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.AnalyzeMoveResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.AnalyzeMoveResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.analyze_move(request) + + expected_params = [ + ( + "destinationParent", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_move_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_move._get_unset_required_fields({}) + assert set(unset_fields) == (set(("destinationParent", "view", )) & set(("resource", "destinationParent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_move_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_move") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_move") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.AnalyzeMoveRequest.pb(asset_service.AnalyzeMoveRequest()) + 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 = asset_service.AnalyzeMoveResponse.to_json(asset_service.AnalyzeMoveResponse()) + + request = asset_service.AnalyzeMoveRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.AnalyzeMoveResponse() + + client.analyze_move(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_move_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeMoveRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'resource': 'sample1/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.analyze_move(request) + + +def test_analyze_move_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.QueryAssetsRequest, + dict, +]) +def test_query_assets_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.QueryAssetsResponse( + job_reference='job_reference_value', + done=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.QueryAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.query_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.QueryAssetsResponse) + assert response.job_reference == 'job_reference_value' + assert response.done is True + + +def test_query_assets_rest_required_fields(request_type=asset_service.QueryAssetsRequest): + transport_class = transports.AssetServiceRestTransport + + 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()).query_assets._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()).query_assets._get_unset_required_fields(jsonified_request) + 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.QueryAssetsResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.QueryAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.query_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_query_assets_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.query_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_query_assets_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_query_assets") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_query_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.QueryAssetsRequest.pb(asset_service.QueryAssetsRequest()) + 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 = asset_service.QueryAssetsResponse.to_json(asset_service.QueryAssetsResponse()) + + request = asset_service.QueryAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.QueryAssetsResponse() + + client.query_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_query_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.QueryAssetsRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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.query_assets(request) + + +def test_query_assets_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.CreateSavedQueryRequest, + dict, +]) +def test_create_saved_query_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/sample2'} + request_init["saved_query"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'creator': 'creator_value', 'last_update_time': {}, 'last_updater': 'last_updater_value', 'labels': {}, 'content': {'iam_policy_analysis_query': {'scope': 'scope_value', 'resource_selector': {'full_resource_name': 'full_resource_name_value'}, 'identity_selector': {'identity': 'identity_value'}, 'access_selector': {'roles': ['roles_value1', 'roles_value2'], 'permissions': ['permissions_value1', 'permissions_value2']}, 'options': {'expand_groups': True, 'expand_roles': True, 'expand_resources': True, 'output_resource_edges': True, 'output_group_edges': True, 'analyze_service_account_impersonation': True}, 'condition_context': {'access_time': {}}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = asset_service.CreateSavedQueryRequest.meta.fields["saved_query"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + else: + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + for field, value in request_init["saved_query"].items(): + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + for subfield_to_delete in subfields_not_in_runtime: + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["saved_query"][field])): + del request_init["saved_query"][field][i][subfield] + else: + del request_init["saved_query"][field][subfield] + 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 = asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_saved_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +def test_create_saved_query_rest_required_fields(request_type=asset_service.CreateSavedQueryRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["saved_query_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 "savedQueryId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_saved_query._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "savedQueryId" in jsonified_request + assert jsonified_request["savedQueryId"] == request_init["saved_query_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["savedQueryId"] = 'saved_query_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_saved_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("saved_query_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 "savedQueryId" in jsonified_request + assert jsonified_request["savedQueryId"] == 'saved_query_id_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.SavedQuery() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_saved_query(request) + + expected_params = [ + ( + "savedQueryId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_saved_query_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_saved_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(("savedQueryId", )) & set(("parent", "savedQuery", "savedQueryId", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_saved_query_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_create_saved_query") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_create_saved_query") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.CreateSavedQueryRequest.pb(asset_service.CreateSavedQueryRequest()) + 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 = asset_service.SavedQuery.to_json(asset_service.SavedQuery()) + + request = asset_service.CreateSavedQueryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.SavedQuery() + + client.create_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.CreateSavedQueryRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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.create_saved_query(request) + + +def test_create_saved_query_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.SavedQuery() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + saved_query=asset_service.SavedQuery(name='name_value'), + saved_query_id='saved_query_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_saved_query(**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=*/*}/savedQueries" % client.transport._host, args[1]) + + +def test_create_saved_query_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_saved_query( + asset_service.CreateSavedQueryRequest(), + parent='parent_value', + saved_query=asset_service.SavedQuery(name='name_value'), + saved_query_id='saved_query_id_value', + ) + + +def test_create_saved_query_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.GetSavedQueryRequest, + dict, +]) +def test_get_saved_query_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/savedQueries/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 = asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_saved_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +def test_get_saved_query_rest_required_fields(request_type=asset_service.GetSavedQueryRequest): + transport_class = transports.AssetServiceRestTransport + + 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_saved_query._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_saved_query._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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.SavedQuery() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_saved_query(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_saved_query_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_saved_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_saved_query_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_get_saved_query") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_get_saved_query") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.GetSavedQueryRequest.pb(asset_service.GetSavedQueryRequest()) + 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 = asset_service.SavedQuery.to_json(asset_service.SavedQuery()) + + request = asset_service.GetSavedQueryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.SavedQuery() + + client.get_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.GetSavedQueryRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/savedQueries/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_saved_query(request) + + +def test_get_saved_query_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.SavedQuery() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'sample1/sample2/savedQueries/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 + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_saved_query(**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=*/*/savedQueries/*}" % client.transport._host, args[1]) + + +def test_get_saved_query_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_saved_query( + asset_service.GetSavedQueryRequest(), + name='name_value', + ) + + +def test_get_saved_query_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListSavedQueriesRequest, + dict, +]) +def test_list_saved_queries_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.ListSavedQueriesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.ListSavedQueriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_saved_queries(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSavedQueriesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_saved_queries_rest_required_fields(request_type=asset_service.ListSavedQueriesRequest): + transport_class = transports.AssetServiceRestTransport + + 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_saved_queries._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_saved_queries._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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.ListSavedQueriesResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.ListSavedQueriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_saved_queries(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_saved_queries_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_saved_queries._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_saved_queries_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_saved_queries") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_saved_queries") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.ListSavedQueriesRequest.pb(asset_service.ListSavedQueriesRequest()) + 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 = asset_service.ListSavedQueriesResponse.to_json(asset_service.ListSavedQueriesResponse()) + + request = asset_service.ListSavedQueriesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.ListSavedQueriesResponse() + + client.list_saved_queries(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_saved_queries_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListSavedQueriesRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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_saved_queries(request) + + +def test_list_saved_queries_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.ListSavedQueriesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/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 + # Convert return value to protobuf type + return_value = asset_service.ListSavedQueriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_saved_queries(**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=*/*}/savedQueries" % client.transport._host, args[1]) + + +def test_list_saved_queries_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_saved_queries( + asset_service.ListSavedQueriesRequest(), + parent='parent_value', + ) + + +def test_list_saved_queries_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + next_page_token='abc', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[], + next_page_token='def', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + ], + next_page_token='ghi', + ), + asset_service.ListSavedQueriesResponse( + saved_queries=[ + asset_service.SavedQuery(), + asset_service.SavedQuery(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.ListSavedQueriesResponse.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': 'sample1/sample2'} + + pager = client.list_saved_queries(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.SavedQuery) + for i in results) + + pages = list(client.list_saved_queries(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", [ + asset_service.UpdateSavedQueryRequest, + dict, +]) +def test_update_saved_query_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'saved_query': {'name': 'sample1/sample2/savedQueries/sample3'}} + request_init["saved_query"] = {'name': 'sample1/sample2/savedQueries/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'creator': 'creator_value', 'last_update_time': {}, 'last_updater': 'last_updater_value', 'labels': {}, 'content': {'iam_policy_analysis_query': {'scope': 'scope_value', 'resource_selector': {'full_resource_name': 'full_resource_name_value'}, 'identity_selector': {'identity': 'identity_value'}, 'access_selector': {'roles': ['roles_value1', 'roles_value2'], 'permissions': ['permissions_value1', 'permissions_value2']}, 'options': {'expand_groups': True, 'expand_roles': True, 'expand_resources': True, 'output_resource_edges': True, 'output_group_edges': True, 'analyze_service_account_impersonation': True}, 'condition_context': {'access_time': {}}}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = asset_service.UpdateSavedQueryRequest.meta.fields["saved_query"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + else: + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + for field, value in request_init["saved_query"].items(): + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + for subfield_to_delete in subfields_not_in_runtime: + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["saved_query"][field])): + del request_init["saved_query"][field][i][subfield] + else: + del request_init["saved_query"][field][subfield] + 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 = asset_service.SavedQuery( + name='name_value', + description='description_value', + creator='creator_value', + last_updater='last_updater_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_saved_query(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.SavedQuery) + assert response.name == 'name_value' + assert response.description == 'description_value' + assert response.creator == 'creator_value' + assert response.last_updater == 'last_updater_value' + + +def test_update_saved_query_rest_required_fields(request_type=asset_service.UpdateSavedQueryRequest): + transport_class = transports.AssetServiceRestTransport + + 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_saved_query._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_saved_query._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.SavedQuery() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_saved_query(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_saved_query_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_saved_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("savedQuery", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_saved_query_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_update_saved_query") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_update_saved_query") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.UpdateSavedQueryRequest.pb(asset_service.UpdateSavedQueryRequest()) + 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 = asset_service.SavedQuery.to_json(asset_service.SavedQuery()) + + request = asset_service.UpdateSavedQueryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.SavedQuery() + + client.update_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.UpdateSavedQueryRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'saved_query': {'name': 'sample1/sample2/savedQueries/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.update_saved_query(request) + + +def test_update_saved_query_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.SavedQuery() + + # get arguments that satisfy an http rule for this method + sample_request = {'saved_query': {'name': 'sample1/sample2/savedQueries/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + saved_query=asset_service.SavedQuery(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_saved_query(**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/{saved_query.name=*/*/savedQueries/*}" % client.transport._host, args[1]) + + +def test_update_saved_query_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_saved_query( + asset_service.UpdateSavedQueryRequest(), + saved_query=asset_service.SavedQuery(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_saved_query_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.DeleteSavedQueryRequest, + dict, +]) +def test_delete_saved_query_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/savedQueries/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_saved_query(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_saved_query_rest_required_fields(request_type=asset_service.DeleteSavedQueryRequest): + transport_class = transports.AssetServiceRestTransport + + 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_saved_query._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_saved_query._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 = AssetServiceClient( + 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_saved_query(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_saved_query_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_saved_query._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_saved_query_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "pre_delete_saved_query") as pre: + pre.assert_not_called() + pb_message = asset_service.DeleteSavedQueryRequest.pb(asset_service.DeleteSavedQueryRequest()) + 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 = asset_service.DeleteSavedQueryRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.DeleteSavedQueryRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/savedQueries/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_saved_query(request) + + +def test_delete_saved_query_rest_flattened(): + client = AssetServiceClient( + 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': 'sample1/sample2/savedQueries/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_saved_query(**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=*/*/savedQueries/*}" % client.transport._host, args[1]) + + +def test_delete_saved_query_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_saved_query( + asset_service.DeleteSavedQueryRequest(), + name='name_value', + ) + + +def test_delete_saved_query_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.BatchGetEffectiveIamPoliciesRequest, + dict, +]) +def test_batch_get_effective_iam_policies_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.BatchGetEffectiveIamPoliciesResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.batch_get_effective_iam_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.BatchGetEffectiveIamPoliciesResponse) + + +def test_batch_get_effective_iam_policies_rest_required_fields(request_type=asset_service.BatchGetEffectiveIamPoliciesRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + request_init["names"] = "" + 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 "names" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_get_effective_iam_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "names" in jsonified_request + assert jsonified_request["names"] == request_init["names"] + + jsonified_request["scope"] = 'scope_value' + jsonified_request["names"] = 'names_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_get_effective_iam_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("names", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + assert "names" in jsonified_request + assert jsonified_request["names"] == 'names_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.BatchGetEffectiveIamPoliciesResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.batch_get_effective_iam_policies(request) + + expected_params = [ + ( + "names", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_batch_get_effective_iam_policies_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.batch_get_effective_iam_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("names", )) & set(("scope", "names", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_get_effective_iam_policies_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_batch_get_effective_iam_policies") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_batch_get_effective_iam_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.BatchGetEffectiveIamPoliciesRequest.pb(asset_service.BatchGetEffectiveIamPoliciesRequest()) + 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 = asset_service.BatchGetEffectiveIamPoliciesResponse.to_json(asset_service.BatchGetEffectiveIamPoliciesResponse()) + + request = asset_service.BatchGetEffectiveIamPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.BatchGetEffectiveIamPoliciesResponse() + + client.batch_get_effective_iam_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_get_effective_iam_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.BatchGetEffectiveIamPoliciesRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.batch_get_effective_iam_policies(request) + + +def test_batch_get_effective_iam_policies_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.AnalyzeOrgPoliciesRequest, + dict, +]) +def test_analyze_org_policies_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.AnalyzeOrgPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.analyze_org_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_analyze_org_policies_rest_required_fields(request_type=asset_service.AnalyzeOrgPoliciesRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + request_init["constraint"] = "" + 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 "constraint" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "constraint" in jsonified_request + assert jsonified_request["constraint"] == request_init["constraint"] + + jsonified_request["scope"] = 'scope_value' + jsonified_request["constraint"] = 'constraint_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policies._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("constraint", "filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + assert "constraint" in jsonified_request + assert jsonified_request["constraint"] == 'constraint_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.AnalyzeOrgPoliciesResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.analyze_org_policies(request) + + expected_params = [ + ( + "constraint", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_org_policies_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_org_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("constraint", "filter", "pageSize", "pageToken", )) & set(("scope", "constraint", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_org_policies_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_org_policies") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_org_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.AnalyzeOrgPoliciesRequest.pb(asset_service.AnalyzeOrgPoliciesRequest()) + 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 = asset_service.AnalyzeOrgPoliciesResponse.to_json(asset_service.AnalyzeOrgPoliciesResponse()) + + request = asset_service.AnalyzeOrgPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.AnalyzeOrgPoliciesResponse() + + client.analyze_org_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_org_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeOrgPoliciesRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.analyze_org_policies(request) + + +def test_analyze_org_policies_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.AnalyzeOrgPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'scope': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.analyze_org_policies(**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/{scope=*/*}:analyzeOrgPolicies" % client.transport._host, args[1]) + + +def test_analyze_org_policies_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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.analyze_org_policies( + asset_service.AnalyzeOrgPoliciesRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + + +def test_analyze_org_policies_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPoliciesResponse( + org_policy_results=[ + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.AnalyzeOrgPoliciesResponse.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 = {'scope': 'sample1/sample2'} + + pager = client.analyze_org_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult) + for i in results) + + pages = list(client.analyze_org_policies(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", [ + asset_service.AnalyzeOrgPolicyGovernedContainersRequest, + dict, +]) +def test_analyze_org_policy_governed_containers_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.analyze_org_policy_governed_containers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedContainersPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_analyze_org_policy_governed_containers_rest_required_fields(request_type=asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + request_init["constraint"] = "" + 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 "constraint" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_containers._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "constraint" in jsonified_request + assert jsonified_request["constraint"] == request_init["constraint"] + + jsonified_request["scope"] = 'scope_value' + jsonified_request["constraint"] = 'constraint_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_containers._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("constraint", "filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + assert "constraint" in jsonified_request + assert jsonified_request["constraint"] == 'constraint_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.analyze_org_policy_governed_containers(request) + + expected_params = [ + ( + "constraint", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_org_policy_governed_containers_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_org_policy_governed_containers._get_unset_required_fields({}) + assert set(unset_fields) == (set(("constraint", "filter", "pageSize", "pageToken", )) & set(("scope", "constraint", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_org_policy_governed_containers_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_org_policy_governed_containers") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_org_policy_governed_containers") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.AnalyzeOrgPolicyGovernedContainersRequest.pb(asset_service.AnalyzeOrgPolicyGovernedContainersRequest()) + 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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.to_json(asset_service.AnalyzeOrgPolicyGovernedContainersResponse()) + + request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() + + client.analyze_org_policy_governed_containers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_org_policy_governed_containers_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeOrgPolicyGovernedContainersRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.analyze_org_policy_governed_containers(request) + + +def test_analyze_org_policy_governed_containers_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'scope': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.analyze_org_policy_governed_containers(**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/{scope=*/*}:analyzeOrgPolicyGovernedContainers" % client.transport._host, args[1]) + + +def test_analyze_org_policy_governed_containers_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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.analyze_org_policy_governed_containers( + asset_service.AnalyzeOrgPolicyGovernedContainersRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + + +def test_analyze_org_policy_governed_containers_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse( + governed_containers=[ + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.AnalyzeOrgPolicyGovernedContainersResponse.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 = {'scope': 'sample1/sample2'} + + pager = client.analyze_org_policy_governed_containers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer) + for i in results) + + pages = list(client.analyze_org_policy_governed_containers(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", [ + asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, + dict, +]) +def test_analyze_org_policy_governed_assets_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.analyze_org_policy_governed_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_analyze_org_policy_governed_assets_rest_required_fields(request_type=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + request_init["constraint"] = "" + 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 "constraint" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_assets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "constraint" in jsonified_request + assert jsonified_request["constraint"] == request_init["constraint"] + + jsonified_request["scope"] = 'scope_value' + jsonified_request["constraint"] = 'constraint_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("constraint", "filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + assert "constraint" in jsonified_request + assert jsonified_request["constraint"] == 'constraint_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.analyze_org_policy_governed_assets(request) + + expected_params = [ + ( + "constraint", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_analyze_org_policy_governed_assets_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.analyze_org_policy_governed_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("constraint", "filter", "pageSize", "pageToken", )) & set(("scope", "constraint", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_analyze_org_policy_governed_assets_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_org_policy_governed_assets") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_org_policy_governed_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.pb(asset_service.AnalyzeOrgPolicyGovernedAssetsRequest()) + 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.to_json(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse()) + + request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() + + client.analyze_org_policy_governed_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_analyze_org_policy_governed_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.analyze_org_policy_governed_assets(request) + + +def test_analyze_org_policy_governed_assets_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'scope': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.analyze_org_policy_governed_assets(**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/{scope=*/*}:analyzeOrgPolicyGovernedAssets" % client.transport._host, args[1]) + + +def test_analyze_org_policy_governed_assets_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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.analyze_org_policy_governed_assets( + asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(), + scope='scope_value', + constraint='constraint_value', + filter='filter_value', + ) + + +def test_analyze_org_policy_governed_assets_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='abc', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[], + next_page_token='def', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + next_page_token='ghi', + ), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( + governed_assets=[ + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.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 = {'scope': 'sample1/sample2'} + + pager = client.analyze_org_policy_governed_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset) + for i in results) + + pages = list(client.analyze_org_policy_governed_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AssetServiceClient( + 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 = AssetServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, +]) +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 = AssetServiceClient.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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AssetServiceGrpcTransport, + ) + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'export_assets', + 'list_assets', + 'batch_get_assets_history', + 'create_feed', + 'get_feed', + 'list_feeds', + 'update_feed', + 'delete_feed', + 'search_all_resources', + 'search_all_iam_policies', + 'analyze_iam_policy', + 'analyze_iam_policy_longrunning', + 'analyze_move', + 'query_assets', + 'create_saved_query', + 'get_saved_query', + 'list_saved_queries', + 'update_saved_query', + 'delete_saved_query', + 'batch_get_effective_iam_policies', + 'analyze_org_policies', + 'analyze_org_policy_governed_containers', + 'analyze_org_policy_governed_assets', + 'get_operation', + ) + 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_asset_service_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.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + 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_asset_service_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.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport() + adc.assert_called_once() + + +def test_asset_service_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) + AssetServiceClient() + 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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( + 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_asset_service_rest_lro_client(): + client = AssetServiceClient( + 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_asset_service_host_no_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_asset_service_host_with_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_asset_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AssetServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AssetServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.export_assets._session + session2 = client2.transport.export_assets._session + assert session1 != session2 + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 + session1 = client1.transport.batch_get_assets_history._session + session2 = client2.transport.batch_get_assets_history._session + assert session1 != session2 + session1 = client1.transport.create_feed._session + session2 = client2.transport.create_feed._session + assert session1 != session2 + session1 = client1.transport.get_feed._session + session2 = client2.transport.get_feed._session + assert session1 != session2 + session1 = client1.transport.list_feeds._session + session2 = client2.transport.list_feeds._session + assert session1 != session2 + session1 = client1.transport.update_feed._session + session2 = client2.transport.update_feed._session + assert session1 != session2 + session1 = client1.transport.delete_feed._session + session2 = client2.transport.delete_feed._session + assert session1 != session2 + session1 = client1.transport.search_all_resources._session + session2 = client2.transport.search_all_resources._session + assert session1 != session2 + session1 = client1.transport.search_all_iam_policies._session + session2 = client2.transport.search_all_iam_policies._session + assert session1 != session2 + session1 = client1.transport.analyze_iam_policy._session + session2 = client2.transport.analyze_iam_policy._session + assert session1 != session2 + session1 = client1.transport.analyze_iam_policy_longrunning._session + session2 = client2.transport.analyze_iam_policy_longrunning._session + assert session1 != session2 + session1 = client1.transport.analyze_move._session + session2 = client2.transport.analyze_move._session + assert session1 != session2 + session1 = client1.transport.query_assets._session + session2 = client2.transport.query_assets._session + assert session1 != session2 + session1 = client1.transport.create_saved_query._session + session2 = client2.transport.create_saved_query._session + assert session1 != session2 + session1 = client1.transport.get_saved_query._session + session2 = client2.transport.get_saved_query._session + assert session1 != session2 + session1 = client1.transport.list_saved_queries._session + session2 = client2.transport.list_saved_queries._session + assert session1 != session2 + session1 = client1.transport.update_saved_query._session + session2 = client2.transport.update_saved_query._session + assert session1 != session2 + session1 = client1.transport.delete_saved_query._session + session2 = client2.transport.delete_saved_query._session + assert session1 != session2 + session1 = client1.transport.batch_get_effective_iam_policies._session + session2 = client2.transport.batch_get_effective_iam_policies._session + assert session1 != session2 + session1 = client1.transport.analyze_org_policies._session + session2 = client2.transport.analyze_org_policies._session + assert session1 != session2 + session1 = client1.transport.analyze_org_policy_governed_containers._session + session2 = client2.transport.analyze_org_policy_governed_containers._session + assert session1 != session2 + session1 = client1.transport.analyze_org_policy_governed_assets._session + session2 = client2.transport.analyze_org_policy_governed_assets._session + assert session1 != session2 +def test_asset_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcTransport( + 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_asset_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcAsyncIOTransport( + 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_asset_service_grpc_lro_client(): + client = AssetServiceClient( + 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_asset_service_grpc_lro_async_client(): + client = AssetServiceAsyncClient( + 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_access_level_path(): + access_policy = "squid" + access_level = "clam" + expected = "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) + actual = AssetServiceClient.access_level_path(access_policy, access_level) + assert expected == actual + + +def test_parse_access_level_path(): + expected = { + "access_policy": "whelk", + "access_level": "octopus", + } + path = AssetServiceClient.access_level_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_access_level_path(path) + assert expected == actual + +def test_access_policy_path(): + access_policy = "oyster" + expected = "accessPolicies/{access_policy}".format(access_policy=access_policy, ) + actual = AssetServiceClient.access_policy_path(access_policy) + assert expected == actual + + +def test_parse_access_policy_path(): + expected = { + "access_policy": "nudibranch", + } + path = AssetServiceClient.access_policy_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_access_policy_path(path) + assert expected == actual + +def test_asset_path(): + expected = "*".format() + actual = AssetServiceClient.asset_path() + assert expected == actual + + +def test_parse_asset_path(): + expected = { + } + path = AssetServiceClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_asset_path(path) + assert expected == actual + +def test_feed_path(): + project = "cuttlefish" + feed = "mussel" + expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) + actual = AssetServiceClient.feed_path(project, feed) + assert expected == actual + + +def test_parse_feed_path(): + expected = { + "project": "winkle", + "feed": "nautilus", + } + path = AssetServiceClient.feed_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_feed_path(path) + assert expected == actual + +def test_inventory_path(): + project = "scallop" + location = "abalone" + instance = "squid" + expected = "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) + actual = AssetServiceClient.inventory_path(project, location, instance) + assert expected == actual + + +def test_parse_inventory_path(): + expected = { + "project": "clam", + "location": "whelk", + "instance": "octopus", + } + path = AssetServiceClient.inventory_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_inventory_path(path) + assert expected == actual + +def test_saved_query_path(): + project = "oyster" + saved_query = "nudibranch" + expected = "projects/{project}/savedQueries/{saved_query}".format(project=project, saved_query=saved_query, ) + actual = AssetServiceClient.saved_query_path(project, saved_query) + assert expected == actual + + +def test_parse_saved_query_path(): + expected = { + "project": "cuttlefish", + "saved_query": "mussel", + } + path = AssetServiceClient.saved_query_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_saved_query_path(path) + assert expected == actual + +def test_service_perimeter_path(): + access_policy = "winkle" + service_perimeter = "nautilus" + expected = "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) + actual = AssetServiceClient.service_perimeter_path(access_policy, service_perimeter) + assert expected == actual + + +def test_parse_service_perimeter_path(): + expected = { + "access_policy": "scallop", + "service_perimeter": "abalone", + } + path = AssetServiceClient.service_perimeter_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_service_perimeter_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AssetServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AssetServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AssetServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AssetServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AssetServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AssetServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AssetServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AssetServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AssetServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AssetServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( + 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_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict({'name': 'sample1/sample2/operations/sample3/sample4'}, 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {'name': 'sample1/sample2/operations/sample3/sample4'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # 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_get_operation(transport: str = "grpc"): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AssetServiceClient( + 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 = AssetServiceAsyncClient( + 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_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AssetServiceClient( + 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 = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), +]) +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/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc new file mode 100644 index 00000000..801f6d8a --- /dev/null +++ b/owl-bot-staging/v1p1beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py + google/cloud/asset/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/v1p1beta1/.flake8 b/owl-bot-staging/v1p1beta1/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/.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/v1p1beta1/MANIFEST.in b/owl-bot-staging/v1p1beta1/MANIFEST.in new file mode 100644 index 00000000..165ea472 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/asset *.py +recursive-include google/cloud/asset_v1p1beta1 *.py diff --git a/owl-bot-staging/v1p1beta1/README.rst b/owl-bot-staging/v1p1beta1/README.rst new file mode 100644 index 00000000..110d4086 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Asset 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 Asset 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/v1p1beta1/docs/_static/custom.css b/owl-bot-staging/v1p1beta1/docs/_static/custom.css new file mode 100644 index 00000000..06423be0 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst new file mode 100644 index 00000000..c034bc69 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst @@ -0,0 +1,10 @@ +AssetService +------------------------------ + +.. automodule:: google.cloud.asset_v1p1beta1.services.asset_service + :members: + :inherited-members: + +.. automodule:: google.cloud.asset_v1p1beta1.services.asset_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst new file mode 100644 index 00000000..2839e354 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p1beta1 API +============================================= +.. toctree:: + :maxdepth: 2 + + asset_service diff --git a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst new file mode 100644 index 00000000..0df91774 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Asset v1p1beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p1beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1p1beta1/docs/conf.py b/owl-bot-staging/v1p1beta1/docs/conf.py new file mode 100644 index 00000000..b6b4f094 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-asset 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-asset" +copyright = u"2023, 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 = 'en' + +# 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-asset-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-asset.tex", + u"google-cloud-asset 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-asset", + u"Google Cloud Asset 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-asset", + u"google-cloud-asset Documentation", + author, + "google-cloud-asset", + "GAPIC library for Google Cloud Asset 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/v1p1beta1/docs/index.rst b/owl-bot-staging/v1p1beta1/docs/index.rst new file mode 100644 index 00000000..e52b7a52 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + asset_v1p1beta1/services + asset_v1p1beta1/types diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py new file mode 100644 index 00000000..ea3f160c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.asset_v1p1beta1.services.asset_service.client import AssetServiceClient +from google.cloud.asset_v1p1beta1.services.asset_service.async_client import AssetServiceAsyncClient + +from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllIamPoliciesRequest +from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllIamPoliciesResponse +from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllResourcesRequest +from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllResourcesResponse +from google.cloud.asset_v1p1beta1.types.assets import IamPolicySearchResult +from google.cloud.asset_v1p1beta1.types.assets import Permissions +from google.cloud.asset_v1p1beta1.types.assets import StandardResourceMetadata + +__all__ = ('AssetServiceClient', + 'AssetServiceAsyncClient', + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'IamPolicySearchResult', + 'Permissions', + 'StandardResourceMetadata', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py new file mode 100644 index 00000000..ad399661 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset_v1p1beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + +from .types.asset_service import SearchAllIamPoliciesRequest +from .types.asset_service import SearchAllIamPoliciesResponse +from .types.asset_service import SearchAllResourcesRequest +from .types.asset_service import SearchAllResourcesResponse +from .types.assets import IamPolicySearchResult +from .types.assets import Permissions +from .types.assets import StandardResourceMetadata + +__all__ = ( + 'AssetServiceAsyncClient', +'AssetServiceClient', +'IamPolicySearchResult', +'Permissions', +'SearchAllIamPoliciesRequest', +'SearchAllIamPoliciesResponse', +'SearchAllResourcesRequest', +'SearchAllResourcesResponse', +'StandardResourceMetadata', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json new file mode 100644 index 00000000..c8f50c01 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1p1beta1", + "protoPackage": "google.cloud.asset.v1p1beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + } + } + }, + "rest": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py new file mode 100644 index 00000000..89a37dc9 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py new file mode 100644 index 00000000..542f923f --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient + +__all__ = ( + 'AssetServiceClient', + 'AssetServiceAsyncClient', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..83ca1005 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py @@ -0,0 +1,494 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.asset_v1p1beta1 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.cloud.asset_v1p1beta1.services.asset_service import pagers +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AssetServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AssetServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AssetServiceClient.common_project_path) + parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) + common_location_path = staticmethod(AssetServiceClient.common_location_path) + parse_common_location_path = staticmethod(AssetServiceClient.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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def search_all_resources(self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesAsyncPager: + r"""Searches all the resources within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + resources within a scope, even if they don't have ``.get`` + permission of all the resources. Callers should have + ``cloud.assets.SearchAllResources`` permission on the requested + scope, otherwise the request will be rejected. + + .. 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 asset_v1p1beta1 + + async def sample_search_all_resources(): + # Create a client + client = asset_v1p1beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest, dict]]): + The request object. Search all resources request. + scope (:class:`str`): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number (such as "folders/1234") + - Project number (such as "projects/12345") + - Project ID (such as "projects/abc") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (:class:`MutableSequence[str]`): + Optional. A list of asset types that + this request searches for. If empty, it + will search all the supported asset + types. + + This corresponds to the ``asset_types`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesAsyncPager: + Search all resources response. + + 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([scope, query, asset_types]) + 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 = asset_service.SearchAllResourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types: + request.asset_types.extend(asset_types) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_resources, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.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(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllResourcesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def search_all_iam_policies(self, + request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesAsyncPager: + r"""Searches all the IAM policies within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + IAM policies within a scope, even if they don't have + ``.getIamPolicy`` permission of all the IAM policies. Callers + should have ``cloud.assets.SearchAllIamPolicies`` permission on + the requested scope, otherwise the request will be rejected. + + .. 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 asset_v1p1beta1 + + async def sample_search_all_iam_policies(): + # Create a client + client = asset_v1p1beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest, dict]]): + The request object. Search all IAM policies request. + scope (:class:`str`): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number (such as "folders/1234") + - Project number (such as "projects/12345") + - Project ID (such as "projects/abc") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (:class:`str`): + Optional. The query statement. Examples: + + - "policy:myuser@mydomain.com" + - "policy:(myuser@mydomain.com viewer)" + + This corresponds to the ``query`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager: + Search all IAM policies response. + + 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([scope, query]) + 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 = asset_service.SearchAllIamPoliciesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.search_all_iam_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.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(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllIamPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AssetServiceAsyncClient": + 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__ = ( + "AssetServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py new file mode 100644 index 00000000..09df402f --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py @@ -0,0 +1,679 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.asset_v1p1beta1 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.cloud.asset_v1p1beta1.services.asset_service import pagers +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .transports.rest import AssetServiceRestTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService 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[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AssetServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AssetServiceTransport]: + """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 AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @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 = "cloudasset.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: + AssetServiceClient: 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: + AssetServiceClient: 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) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @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, AssetServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): + # transport is a AssetServiceTransport 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 search_all_resources(self, + request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + asset_types: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesPager: + r"""Searches all the resources within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + resources within a scope, even if they don't have ``.get`` + permission of all the resources. Callers should have + ``cloud.assets.SearchAllResources`` permission on the requested + scope, otherwise the request will be rejected. + + .. 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 asset_v1p1beta1 + + def sample_search_all_resources(): + # Create a client + client = asset_v1p1beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest, dict]): + The request object. Search all resources request. + scope (str): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number (such as "folders/1234") + - Project number (such as "projects/12345") + - Project ID (such as "projects/abc") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + Optional. The query statement. + This corresponds to the ``query`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + asset_types (MutableSequence[str]): + Optional. A list of asset types that + this request searches for. If empty, it + will search all the supported asset + types. + + This corresponds to the ``asset_types`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesPager: + Search all resources response. + + 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([scope, query, asset_types]) + 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 asset_service.SearchAllResourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllResourcesRequest): + request = asset_service.SearchAllResourcesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + if asset_types is not None: + request.asset_types = asset_types + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_resources] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllResourcesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def search_all_iam_policies(self, + request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, + *, + scope: Optional[str] = None, + query: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesPager: + r"""Searches all the IAM policies within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + IAM policies within a scope, even if they don't have + ``.getIamPolicy`` permission of all the IAM policies. Callers + should have ``cloud.assets.SearchAllIamPolicies`` permission on + the requested scope, otherwise the request will be rejected. + + .. 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 asset_v1p1beta1 + + def sample_search_all_iam_policies(): + # Create a client + client = asset_v1p1beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest, dict]): + The request object. Search all IAM policies request. + scope (str): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The + allowed value must be: + + - Organization number (such as "organizations/123") + - Folder number (such as "folders/1234") + - Project number (such as "projects/12345") + - Project ID (such as "projects/abc") + + This corresponds to the ``scope`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + query (str): + Optional. The query statement. Examples: + + - "policy:myuser@mydomain.com" + - "policy:(myuser@mydomain.com viewer)" + + This corresponds to the ``query`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesPager: + Search all IAM policies response. + + 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([scope, query]) + 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 asset_service.SearchAllIamPoliciesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): + request = asset_service.SearchAllIamPoliciesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scope is not None: + request.scope = scope + if query is not None: + request.query = query + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.search_all_iam_policies] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("scope", request.scope), + )), + ) + + # 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.SearchAllIamPoliciesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AssetServiceClient": + 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() + + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AssetServiceClient", +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py new file mode 100644 index 00000000..d8499278 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py @@ -0,0 +1,261 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets + + +class SearchAllResourcesPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` + 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[..., asset_service.SearchAllResourcesResponse], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + 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.asset_v1p1beta1.types.SearchAllResourcesRequest): + The initial request object. + response (google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse): + 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 = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.SearchAllResourcesResponse]: + 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[assets.StandardResourceMetadata]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAllResourcesAsyncPager: + """A pager for iterating through ``search_all_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllResources`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` + 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[asset_service.SearchAllResourcesResponse]], + request: asset_service.SearchAllResourcesRequest, + response: asset_service.SearchAllResourcesResponse, + *, + 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.asset_v1p1beta1.types.SearchAllResourcesRequest): + The initial request object. + response (google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse): + 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 = asset_service.SearchAllResourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.SearchAllResourcesResponse]: + 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[assets.StandardResourceMetadata]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` + 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[..., asset_service.SearchAllIamPoliciesResponse], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + 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.asset_v1p1beta1.types.SearchAllIamPoliciesRequest): + The initial request object. + response (google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse): + 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 = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.SearchAllIamPoliciesResponse]: + 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[assets.IamPolicySearchResult]: + for page in self.pages: + yield from page.results + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class SearchAllIamPoliciesAsyncPager: + """A pager for iterating through ``search_all_iam_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``SearchAllIamPolicies`` requests and continue to iterate + through the ``results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` + 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[asset_service.SearchAllIamPoliciesResponse]], + request: asset_service.SearchAllIamPoliciesRequest, + response: asset_service.SearchAllIamPoliciesResponse, + *, + 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.asset_v1p1beta1.types.SearchAllIamPoliciesRequest): + The initial request object. + response (google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse): + 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 = asset_service.SearchAllIamPoliciesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.SearchAllIamPoliciesResponse]: + 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[assets.IamPolicySearchResult]: + async def async_generator(): + async for page in self.pages: + for response in page.results: + 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/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..c34a5f8f --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .rest import AssetServiceRestTransport +from .rest import AssetServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AssetServiceRestTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', + 'AssetServiceRestTransport', + 'AssetServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..0af6e37c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.asset_v1p1beta1 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.cloud.asset_v1p1beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudasset.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.search_all_resources: gapic_v1.method.wrap_method( + self.search_all_resources, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.search_all_iam_policies: gapic_v1.method.wrap_method( + self.search_all_iam_policies, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.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 search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Union[ + asset_service.SearchAllResourcesResponse, + Awaitable[asset_service.SearchAllResourcesResponse] + ]]: + raise NotImplementedError() + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Union[ + asset_service.SearchAllIamPoliciesResponse, + Awaitable[asset_service.SearchAllIamPoliciesResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AssetServiceTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..ddb025c0 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,303 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.asset_v1p1beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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 search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all the resources within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + resources within a scope, even if they don't have ``.get`` + permission of all the resources. Callers should have + ``cloud.assets.SearchAllResources`` permission on the requested + scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + ~.SearchAllResourcesResponse]: + 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 'search_all_resources' not in self._stubs: + self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources', + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs['search_all_resources'] + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all the IAM policies within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + IAM policies within a scope, even if they don't have + ``.getIamPolicy`` permission of all the IAM policies. Callers + should have ``cloud.assets.SearchAllIamPolicies`` permission on + the requested scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + ~.SearchAllIamPoliciesResponse]: + 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 'search_all_iam_policies' not in self._stubs: + self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies', + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs['search_all_iam_policies'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AssetServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2801d4b7 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.asset_v1p1beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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 search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + Awaitable[asset_service.SearchAllResourcesResponse]]: + r"""Return a callable for the search all resources method over gRPC. + + Searches all the resources within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + resources within a scope, even if they don't have ``.get`` + permission of all the resources. Callers should have + ``cloud.assets.SearchAllResources`` permission on the requested + scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllResourcesRequest], + Awaitable[~.SearchAllResourcesResponse]]: + 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 'search_all_resources' not in self._stubs: + self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources', + request_serializer=asset_service.SearchAllResourcesRequest.serialize, + response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, + ) + return self._stubs['search_all_resources'] + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + Awaitable[asset_service.SearchAllIamPoliciesResponse]]: + r"""Return a callable for the search all iam policies method over gRPC. + + Searches all the IAM policies within a given accessible Resource + Manager scope (project/folder/organization). This RPC gives + callers especially administrators the ability to search all the + IAM policies within a scope, even if they don't have + ``.getIamPolicy`` permission of all the IAM policies. Callers + should have ``cloud.assets.SearchAllIamPolicies`` permission on + the requested scope, otherwise the request will be rejected. + + Returns: + Callable[[~.SearchAllIamPoliciesRequest], + Awaitable[~.SearchAllIamPoliciesResponse]]: + 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 'search_all_iam_policies' not in self._stubs: + self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies', + request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, + response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, + ) + return self._stubs['search_all_iam_policies'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py new file mode 100644 index 00000000..e76c75c3 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py @@ -0,0 +1,399 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +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 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.asset_v1p1beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: + """Interceptor for AssetService. + + 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 AssetServiceRestTransport. + + .. code-block:: python + class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): + def pre_search_all_iam_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_all_iam_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_all_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_all_resources(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) + client = AssetServiceClient(transport=transport) + + + """ + def pre_search_all_iam_policies(self, request: asset_service.SearchAllIamPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllIamPoliciesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_all_iam_policies + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_search_all_iam_policies(self, response: asset_service.SearchAllIamPoliciesResponse) -> asset_service.SearchAllIamPoliciesResponse: + """Post-rpc interceptor for search_all_iam_policies + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_search_all_resources(self, request: asset_service.SearchAllResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllResourcesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_all_resources + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_search_all_resources(self, response: asset_service.SearchAllResourcesResponse) -> asset_service.SearchAllResourcesResponse: + """Post-rpc interceptor for search_all_resources + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AssetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AssetServiceRestInterceptor + + +class AssetServiceRestTransport(AssetServiceTransport): + """REST backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _SearchAllIamPolicies(AssetServiceRestStub): + def __hash__(self): + return hash("SearchAllIamPolicies") + + __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: asset_service.SearchAllIamPoliciesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.SearchAllIamPoliciesResponse: + r"""Call the search all iam policies method over HTTP. + + Args: + request (~.asset_service.SearchAllIamPoliciesRequest): + The request object. Search all IAM policies request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.SearchAllIamPoliciesResponse: + Search all IAM policies response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{scope=*/*}/iamPolicies:searchAll', + }, + ] + request, metadata = self._interceptor.pre_search_all_iam_policies(request, metadata) + pb_request = asset_service.SearchAllIamPoliciesRequest.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 = asset_service.SearchAllIamPoliciesResponse() + pb_resp = asset_service.SearchAllIamPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_all_iam_policies(resp) + return resp + + class _SearchAllResources(AssetServiceRestStub): + def __hash__(self): + return hash("SearchAllResources") + + __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: asset_service.SearchAllResourcesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.SearchAllResourcesResponse: + r"""Call the search all resources method over HTTP. + + Args: + request (~.asset_service.SearchAllResourcesRequest): + The request object. Search all resources request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.SearchAllResourcesResponse: + Search all resources response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p1beta1/{scope=*/*}/resources:searchAll', + }, + ] + request, metadata = self._interceptor.pre_search_all_resources(request, metadata) + pb_request = asset_service.SearchAllResourcesRequest.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 = asset_service.SearchAllResourcesResponse() + pb_resp = asset_service.SearchAllResourcesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_all_resources(resp) + return resp + + @property + def search_all_iam_policies(self) -> Callable[ + [asset_service.SearchAllIamPoliciesRequest], + asset_service.SearchAllIamPoliciesResponse]: + # 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._SearchAllIamPolicies(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_all_resources(self) -> Callable[ + [asset_service.SearchAllResourcesRequest], + asset_service.SearchAllResourcesResponse]: + # 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._SearchAllResources(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AssetServiceRestTransport', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py new file mode 100644 index 00000000..6053b9ff --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .asset_service import ( + SearchAllIamPoliciesRequest, + SearchAllIamPoliciesResponse, + SearchAllResourcesRequest, + SearchAllResourcesResponse, +) +from .assets import ( + IamPolicySearchResult, + Permissions, + StandardResourceMetadata, +) + +__all__ = ( + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'IamPolicySearchResult', + 'Permissions', + 'StandardResourceMetadata', +) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py new file mode 100644 index 00000000..3d5c996a --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py @@ -0,0 +1,212 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.asset_v1p1beta1.types import assets + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p1beta1', + manifest={ + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + }, +) + + +class SearchAllResourcesRequest(proto.Message): + r"""Search all resources request. + + Attributes: + scope (str): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The allowed + value must be: + + - Organization number (such as "organizations/123") + - Folder number (such as "folders/1234") + - Project number (such as "projects/12345") + - Project ID (such as "projects/abc") + query (str): + Optional. The query statement. + asset_types (MutableSequence[str]): + Optional. A list of asset types that this + request searches for. If empty, it will search + all the supported asset types. + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero, server will pick an appropriate default. + Returned results may be fewer than requested. When this + happens, there could be more results as long as + ``next_page_token`` is returned. + page_token (str): + Optional. If present, then retrieve the next batch of + results from the preceding call to this method. + ``page_token`` must be the value of ``next_page_token`` from + the previous response. The values of all other method + parameters, must be identical to those in the previous call. + order_by (str): + Optional. A comma separated list of fields specifying the + sorting order of the results. The default order is + ascending. Add ``DESC`` after the field name to indicate + descending order. Redundant space characters are ignored. + For example, ``location DESC , name``. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + page_size: int = proto.Field( + proto.INT32, + number=4, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=10, + ) + + +class SearchAllResourcesResponse(proto.Message): + r"""Search all resources response. + + Attributes: + results (MutableSequence[google.cloud.asset_v1p1beta1.types.StandardResourceMetadata]): + A list of resource that match the search + query. + next_page_token (str): + If there are more results than those appearing in this + response, then ``next_page_token`` is included. To get the + next set of results, call this method again using the value + of ``next_page_token`` as ``page_token``. + """ + + @property + def raw_page(self): + return self + + results: MutableSequence[assets.StandardResourceMetadata] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=assets.StandardResourceMetadata, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SearchAllIamPoliciesRequest(proto.Message): + r"""Search all IAM policies request. + + Attributes: + scope (str): + Required. The relative name of an asset. The search is + limited to the resources within the ``scope``. The allowed + value must be: + + - Organization number (such as "organizations/123") + - Folder number (such as "folders/1234") + - Project number (such as "projects/12345") + - Project ID (such as "projects/abc") + query (str): + Optional. The query statement. Examples: + + - "policy:myuser@mydomain.com" + - "policy:(myuser@mydomain.com viewer)". + page_size (int): + Optional. The page size for search result pagination. Page + size is capped at 500 even if a larger value is given. If + set to zero, server will pick an appropriate default. + Returned results may be fewer than requested. When this + happens, there could be more results as long as + ``next_page_token`` is returned. + page_token (str): + Optional. If present, retrieve the next batch of results + from the preceding call to this method. ``page_token`` must + be the value of ``next_page_token`` from the previous + response. The values of all other method parameters must be + identical to those in the previous call. + """ + + scope: str = proto.Field( + proto.STRING, + number=1, + ) + query: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchAllIamPoliciesResponse(proto.Message): + r"""Search all IAM policies response. + + Attributes: + results (MutableSequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult]): + A list of IAM policies that match the search + query. Related information such as the + associated resource is returned along with the + policy. + next_page_token (str): + Set if there are more results than those appearing in this + response; to get the next set of results, call this method + again, using this value as the ``page_token``. + """ + + @property + def raw_page(self): + return self + + results: MutableSequence[assets.IamPolicySearchResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=assets.IamPolicySearchResult, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py new file mode 100644 index 00000000..28a1077f --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.iam.v1 import policy_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p1beta1', + manifest={ + 'StandardResourceMetadata', + 'IamPolicySearchResult', + 'Permissions', + }, +) + + +class StandardResourceMetadata(proto.Message): + r"""The standard metadata of a cloud resource. + + Attributes: + name (str): + The full resource name. For example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more information. + asset_type (str): + The type of this resource. + For example: "compute.googleapis.com/Disk". + project (str): + The project that this resource belongs to, in the form of + ``projects/{project_number}``. + display_name (str): + The display name of this resource. + description (str): + One or more paragraphs of text description of + this resource. Maximum length could be up to 1M + bytes. + additional_attributes (MutableSequence[str]): + Additional searchable attributes of this + resource. Informational only. The exact set of + attributes is subject to change. For example: + project id, DNS name etc. + location (str): + Location can be "global", regional like + "us-east1", or zonal like "us-west1-b". + labels (MutableMapping[str, str]): + Labels associated with this resource. See `Labelling and + grouping Google Cloud + resources `__ + for more information. + network_tags (MutableSequence[str]): + Network tags associated with this resource. Like labels, + network tags are a type of annotations used to group Google + Cloud resources. See `Labelling Google Cloud + resources `__ + for more information. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_type: str = proto.Field( + proto.STRING, + number=2, + ) + project: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + additional_attributes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + location: str = proto.Field( + proto.STRING, + number=11, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + network_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=13, + ) + + +class IamPolicySearchResult(proto.Message): + r"""The result for an IAM policy search. + + Attributes: + resource (str): + The `full resource + name `__ + of the resource associated with this IAM policy. + project (str): + The project that the associated Google Cloud resource + belongs to, in the form of ``projects/{project_number}``. If + an IAM policy is set on a resource -- such as a Compute + Engine instance or a Cloud Storage bucket -- the project + field will indicate the project that contains the resource. + If an IAM policy is set on a folder or orgnization, the + project field will be empty. + policy (google.iam.v1.policy_pb2.Policy): + The IAM policy attached to the specified + resource. Note that the original IAM policy can + contain multiple bindings. This only contains + the bindings that match the given query. For + queries that don't contain a constraint on + policies (e.g. an empty query), this contains + all the bindings. + explanation (google.cloud.asset_v1p1beta1.types.IamPolicySearchResult.Explanation): + Explanation about the IAM policy search + result. It contains additional information that + explains why the search result matches the + query. + """ + + class Explanation(proto.Message): + r"""Explanation about the IAM policy search result. + + Attributes: + matched_permissions (MutableMapping[str, google.cloud.asset_v1p1beta1.types.Permissions]): + The map from roles to their included permission matching the + permission query (e.g. containing + ``policy.role.permissions:``). Example role string: + "roles/compute.instanceAdmin". The roles can also be found + in the returned ``policy`` bindings. Note that the map is + populated only if requesting with a permission query. + """ + + matched_permissions: MutableMapping[str, 'Permissions'] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='Permissions', + ) + + resource: str = proto.Field( + proto.STRING, + number=1, + ) + project: str = proto.Field( + proto.STRING, + number=3, + ) + policy: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + explanation: Explanation = proto.Field( + proto.MESSAGE, + number=5, + message=Explanation, + ) + + +class Permissions(proto.Message): + r"""IAM permissions. + + Attributes: + permissions (MutableSequence[str]): + A list of permissions. Example permission + string: "compute.disk.get". + """ + + permissions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/mypy.ini b/owl-bot-staging/v1p1beta1/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1p1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1p1beta1/noxfile.py b/owl-bot-staging/v1p1beta1/noxfile.py new file mode 100644 index 00000000..b9d4c480 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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/asset_v1p1beta1/', + '--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==7.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/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py new file mode 100644 index 00000000..eeab16da --- /dev/null +++ b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllIamPolicies +# 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-asset + + +# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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 asset_v1p1beta1 + + +async def sample_search_all_iam_policies(): + # Create a client + client = asset_v1p1beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_async] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py new file mode 100644 index 00000000..1198c482 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllIamPolicies +# 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-asset + + +# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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 asset_v1p1beta1 + + +def sample_search_all_iam_policies(): + # Create a client + client = asset_v1p1beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllIamPoliciesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_iam_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_sync] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py new file mode 100644 index 00000000..173f0087 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllResources +# 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-asset + + +# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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 asset_v1p1beta1 + + +async def sample_search_all_resources(): + # Create a client + client = asset_v1p1beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_async] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py new file mode 100644 index 00000000..fe079175 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchAllResources +# 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-asset + + +# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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 asset_v1p1beta1 + + +def sample_search_all_resources(): + # Create a client + client = asset_v1p1beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p1beta1.SearchAllResourcesRequest( + scope="scope_value", + ) + + # Make the request + page_result = client.search_all_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_sync] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json b/owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json new file mode 100644 index 00000000..dcbeb822 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json @@ -0,0 +1,361 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.asset.v1p1beta1", + "version": "v1p1beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-asset", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient.search_all_iam_policies", + "method": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllIamPolicies", + "service": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllIamPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager", + "shortName": "search_all_iam_policies" + }, + "description": "Sample for SearchAllIamPolicies", + "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient.search_all_iam_policies", + "method": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllIamPolicies", + "service": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllIamPolicies" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesPager", + "shortName": "search_all_iam_policies" + }, + "description": "Sample for SearchAllIamPolicies", + "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient.search_all_resources", + "method": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllResources", + "service": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "asset_types", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesAsyncPager", + "shortName": "search_all_resources" + }, + "description": "Sample for SearchAllResources", + "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient.search_all_resources", + "method": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllResources", + "service": { + "fullName": "google.cloud.asset.v1p1beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "SearchAllResources" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest" + }, + { + "name": "scope", + "type": "str" + }, + { + "name": "query", + "type": "str" + }, + { + "name": "asset_types", + "type": "MutableSequence[str]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesPager", + "shortName": "search_all_resources" + }, + "description": "Sample for SearchAllResources", + "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py b/owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py new file mode 100644 index 00000000..1846c478 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), + 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), + } + + 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=assetCallTransformer(), +): + """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 asset 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/v1p1beta1/setup.py b/owl-bot-staging/v1p1beta1/setup.py new file mode 100644 index 00000000..166120b0 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-asset' + + +description = "Google Cloud Asset API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/asset/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-asset" + +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/v1p1beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.10.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.11.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.12.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.7.txt new file mode 100644 index 00000000..2beecf99 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.8.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.9.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py new file mode 100644 index 00000000..3100699e --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -0,0 +1,2674 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 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.asset_v1p1beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p1beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p1beta1.services.asset_service import pagers +from google.cloud.asset_v1p1beta1.services.asset_service import transports +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +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 AssetServiceClient._get_default_mtls_endpoint(None) is None + assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceRestTransport, + ] + assert transport in available_transports + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_asset_service_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", [ + AssetServiceClient, AssetServiceAsyncClient +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), +]) +def test_asset_service_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_asset_service_client_client_options_from_dict(): + with mock.patch('google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.SearchAllResourcesRequest, + dict, +]) +def test_search_all_resources(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse( + next_page_token='next_page_token_value', + ) + response = client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_resources_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 = AssetServiceClient( + 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.search_all_resources), + '__call__') as call: + client.search_all_resources() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllResourcesRequest() + +@pytest.mark.asyncio +async def test_search_all_resources_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllResourcesRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_all_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllResourcesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_all_resources_async_from_dict(): + await test_search_all_resources_async(request_type=dict) + + +def test_search_all_resources_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + call.return_value = asset_service.SearchAllResourcesResponse() + client.search_all_resources(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_all_resources_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllResourcesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) + await client.search_all_resources(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', + 'scope=scope_value', + ) in kw['metadata'] + + +def test_search_all_resources_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_resources( + scope='scope_value', + query='query_value', + asset_types=['asset_types_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + arg = args[0].asset_types + mock_val = ['asset_types_value'] + assert arg == mock_val + + +def test_search_all_resources_flattened_error(): + client = AssetServiceClient( + 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.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllResourcesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_resources( + scope='scope_value', + query='query_value', + asset_types=['asset_types_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + arg = args[0].asset_types + mock_val = ['asset_types_value'] + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_all_resources_flattened_error_async(): + client = AssetServiceAsyncClient( + 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.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + + +def test_search_all_resources_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('scope', ''), + )), + ) + pager = client.search_all_resources(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.StandardResourceMetadata) + for i in results) +def test_search_all_resources_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_resources), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + pages = list(client.search_all_resources(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_search_all_resources_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_all_resources(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, assets.StandardResourceMetadata) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_resources_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_resources), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_all_resources(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + asset_service.SearchAllIamPoliciesRequest, + dict, +]) +def test_search_all_iam_policies(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse( + next_page_token='next_page_token_value', + ) + response = client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_iam_policies_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 = AssetServiceClient( + 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.search_all_iam_policies), + '__call__') as call: + client.search_all_iam_policies() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllIamPoliciesRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse( + next_page_token='next_page_token_value', + )) + response = await client.search_all_iam_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.SearchAllIamPoliciesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_from_dict(): + await test_search_all_iam_policies_async(request_type=dict) + + +def test_search_all_iam_policies_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + call.return_value = asset_service.SearchAllIamPoliciesResponse() + client.search_all_iam_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.SearchAllIamPoliciesRequest() + + request.scope = 'scope_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) + await client.search_all_iam_policies(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', + 'scope=scope_value', + ) in kw['metadata'] + + +def test_search_all_iam_policies_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.search_all_iam_policies( + scope='scope_value', + query='query_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + + +def test_search_all_iam_policies_flattened_error(): + client = AssetServiceClient( + 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.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope='scope_value', + query='query_value', + ) + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.SearchAllIamPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.search_all_iam_policies( + scope='scope_value', + query='query_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].scope + mock_val = 'scope_value' + assert arg == mock_val + arg = args[0].query + mock_val = 'query_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_search_all_iam_policies_flattened_error_async(): + client = AssetServiceAsyncClient( + 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.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope='scope_value', + query='query_value', + ) + + +def test_search_all_iam_policies_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_iam_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('scope', ''), + )), + ) + pager = client.search_all_iam_policies(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) + for i in results) +def test_search_all_iam_policies_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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.search_all_iam_policies), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = list(client.search_all_iam_policies(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_search_all_iam_policies_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.search_all_iam_policies(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, assets.IamPolicySearchResult) + for i in responses) + + +@pytest.mark.asyncio +async def test_search_all_iam_policies_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.search_all_iam_policies), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.search_all_iam_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + asset_service.SearchAllResourcesRequest, + dict, +]) +def test_search_all_resources_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.SearchAllResourcesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_all_resources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllResourcesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_resources_rest_required_fields(request_type=asset_service.SearchAllResourcesRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + 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()).search_all_resources._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scope"] = 'scope_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_resources._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_types", "order_by", "page_size", "page_token", "query", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.SearchAllResourcesResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_all_resources(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_all_resources_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_all_resources._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetTypes", "orderBy", "pageSize", "pageToken", "query", )) & set(("scope", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_all_resources_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_resources") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_resources") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.SearchAllResourcesRequest.pb(asset_service.SearchAllResourcesRequest()) + 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 = asset_service.SearchAllResourcesResponse.to_json(asset_service.SearchAllResourcesResponse()) + + request = asset_service.SearchAllResourcesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.SearchAllResourcesResponse() + + client.search_all_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_all_resources_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllResourcesRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.search_all_resources(request) + + +def test_search_all_resources_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.SearchAllResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'scope': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.search_all_resources(**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/v1p1beta1/{scope=*/*}/resources:searchAll" % client.transport._host, args[1]) + + +def test_search_all_resources_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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.search_all_resources( + asset_service.SearchAllResourcesRequest(), + scope='scope_value', + query='query_value', + asset_types=['asset_types_value'], + ) + + +def test_search_all_resources_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + next_page_token='abc', + ), + asset_service.SearchAllResourcesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllResourcesResponse( + results=[ + assets.StandardResourceMetadata(), + assets.StandardResourceMetadata(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.SearchAllResourcesResponse.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 = {'scope': 'sample1/sample2'} + + pager = client.search_all_resources(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.StandardResourceMetadata) + for i in results) + + pages = list(client.search_all_resources(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", [ + asset_service.SearchAllIamPoliciesRequest, + dict, +]) +def test_search_all_iam_policies_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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 = asset_service.SearchAllIamPoliciesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.search_all_iam_policies(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllIamPoliciesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_search_all_iam_policies_rest_required_fields(request_type=asset_service.SearchAllIamPoliciesRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["scope"] = "" + 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()).search_all_iam_policies._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["scope"] = 'scope_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_iam_policies._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", "query", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "scope" in jsonified_request + assert jsonified_request["scope"] == 'scope_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.SearchAllIamPoliciesResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.search_all_iam_policies(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_search_all_iam_policies_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.search_all_iam_policies._get_unset_required_fields({}) + assert set(unset_fields) == (set(("pageSize", "pageToken", "query", )) & set(("scope", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_all_iam_policies_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_iam_policies") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_iam_policies") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.SearchAllIamPoliciesRequest.pb(asset_service.SearchAllIamPoliciesRequest()) + 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 = asset_service.SearchAllIamPoliciesResponse.to_json(asset_service.SearchAllIamPoliciesResponse()) + + request = asset_service.SearchAllIamPoliciesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.SearchAllIamPoliciesResponse() + + client.search_all_iam_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_all_iam_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllIamPoliciesRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'scope': 'sample1/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.search_all_iam_policies(request) + + +def test_search_all_iam_policies_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.SearchAllIamPoliciesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'scope': 'sample1/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + scope='scope_value', + query='query_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.search_all_iam_policies(**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/v1p1beta1/{scope=*/*}/iamPolicies:searchAll" % client.transport._host, args[1]) + + +def test_search_all_iam_policies_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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.search_all_iam_policies( + asset_service.SearchAllIamPoliciesRequest(), + scope='scope_value', + query='query_value', + ) + + +def test_search_all_iam_policies_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + next_page_token='abc', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[], + next_page_token='def', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + ], + next_page_token='ghi', + ), + asset_service.SearchAllIamPoliciesResponse( + results=[ + assets.IamPolicySearchResult(), + assets.IamPolicySearchResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.SearchAllIamPoliciesResponse.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 = {'scope': 'sample1/sample2'} + + pager = client.search_all_iam_policies(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) + for i in results) + + pages = list(client.search_all_iam_policies(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AssetServiceClient( + 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 = AssetServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, +]) +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 = AssetServiceClient.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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AssetServiceGrpcTransport, + ) + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'search_all_resources', + 'search_all_iam_policies', + ) + 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_asset_service_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.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + 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_asset_service_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.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport() + adc.assert_called_once() + + +def test_asset_service_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) + AssetServiceClient() + 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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( + 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_asset_service_host_no_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_asset_service_host_with_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_asset_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AssetServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AssetServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.search_all_resources._session + session2 = client2.transport.search_all_resources._session + assert session1 != session2 + session1 = client1.transport.search_all_iam_policies._session + session2 = client2.transport.search_all_iam_policies._session + assert session1 != session2 +def test_asset_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcTransport( + 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_asset_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcAsyncIOTransport( + 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AssetServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = AssetServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format(folder=folder, ) + actual = AssetServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = AssetServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AssetServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = AssetServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format(project=project, ) + actual = AssetServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = AssetServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AssetServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = AssetServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( + 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_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AssetServiceClient( + 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 = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), +]) +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/v1p2beta1/.coveragerc b/owl-bot-staging/v1p2beta1/.coveragerc new file mode 100644 index 00000000..801f6d8a --- /dev/null +++ b/owl-bot-staging/v1p2beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py + google/cloud/asset/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/v1p2beta1/.flake8 b/owl-bot-staging/v1p2beta1/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1p2beta1/.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/v1p2beta1/MANIFEST.in b/owl-bot-staging/v1p2beta1/MANIFEST.in new file mode 100644 index 00000000..ff48182d --- /dev/null +++ b/owl-bot-staging/v1p2beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/asset *.py +recursive-include google/cloud/asset_v1p2beta1 *.py diff --git a/owl-bot-staging/v1p2beta1/README.rst b/owl-bot-staging/v1p2beta1/README.rst new file mode 100644 index 00000000..110d4086 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Asset 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 Asset 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/v1p2beta1/docs/_static/custom.css b/owl-bot-staging/v1p2beta1/docs/_static/custom.css new file mode 100644 index 00000000..06423be0 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst new file mode 100644 index 00000000..21bc405a --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst @@ -0,0 +1,6 @@ +AssetService +------------------------------ + +.. automodule:: google.cloud.asset_v1p2beta1.services.asset_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst new file mode 100644 index 00000000..f8ff126c --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p2beta1 API +============================================= +.. toctree:: + :maxdepth: 2 + + asset_service diff --git a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst new file mode 100644 index 00000000..cfbf146e --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Asset v1p2beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p2beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1p2beta1/docs/conf.py b/owl-bot-staging/v1p2beta1/docs/conf.py new file mode 100644 index 00000000..b6b4f094 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-asset 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-asset" +copyright = u"2023, 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 = 'en' + +# 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-asset-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-asset.tex", + u"google-cloud-asset 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-asset", + u"Google Cloud Asset 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-asset", + u"google-cloud-asset Documentation", + author, + "google-cloud-asset", + "GAPIC library for Google Cloud Asset 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/v1p2beta1/docs/index.rst b/owl-bot-staging/v1p2beta1/docs/index.rst new file mode 100644 index 00000000..db16927c --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + asset_v1p2beta1/services + asset_v1p2beta1/types diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py new file mode 100644 index 00000000..d3707f35 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.asset_v1p2beta1.services.asset_service.client import AssetServiceClient +from google.cloud.asset_v1p2beta1.services.asset_service.async_client import AssetServiceAsyncClient + +from google.cloud.asset_v1p2beta1.types.asset_service import CreateFeedRequest +from google.cloud.asset_v1p2beta1.types.asset_service import DeleteFeedRequest +from google.cloud.asset_v1p2beta1.types.asset_service import Feed +from google.cloud.asset_v1p2beta1.types.asset_service import FeedOutputConfig +from google.cloud.asset_v1p2beta1.types.asset_service import GcsDestination +from google.cloud.asset_v1p2beta1.types.asset_service import GetFeedRequest +from google.cloud.asset_v1p2beta1.types.asset_service import ListFeedsRequest +from google.cloud.asset_v1p2beta1.types.asset_service import ListFeedsResponse +from google.cloud.asset_v1p2beta1.types.asset_service import OutputConfig +from google.cloud.asset_v1p2beta1.types.asset_service import PubsubDestination +from google.cloud.asset_v1p2beta1.types.asset_service import UpdateFeedRequest +from google.cloud.asset_v1p2beta1.types.asset_service import ContentType +from google.cloud.asset_v1p2beta1.types.assets import Asset +from google.cloud.asset_v1p2beta1.types.assets import Resource +from google.cloud.asset_v1p2beta1.types.assets import TemporalAsset +from google.cloud.asset_v1p2beta1.types.assets import TimeWindow + +__all__ = ('AssetServiceClient', + 'AssetServiceAsyncClient', + 'CreateFeedRequest', + 'DeleteFeedRequest', + 'Feed', + 'FeedOutputConfig', + 'GcsDestination', + 'GetFeedRequest', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'OutputConfig', + 'PubsubDestination', + 'UpdateFeedRequest', + 'ContentType', + 'Asset', + 'Resource', + 'TemporalAsset', + 'TimeWindow', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py new file mode 100644 index 00000000..257425c0 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset_v1p2beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + +from .types.asset_service import CreateFeedRequest +from .types.asset_service import DeleteFeedRequest +from .types.asset_service import Feed +from .types.asset_service import FeedOutputConfig +from .types.asset_service import GcsDestination +from .types.asset_service import GetFeedRequest +from .types.asset_service import ListFeedsRequest +from .types.asset_service import ListFeedsResponse +from .types.asset_service import OutputConfig +from .types.asset_service import PubsubDestination +from .types.asset_service import UpdateFeedRequest +from .types.asset_service import ContentType +from .types.assets import Asset +from .types.assets import Resource +from .types.assets import TemporalAsset +from .types.assets import TimeWindow + +__all__ = ( + 'AssetServiceAsyncClient', +'Asset', +'AssetServiceClient', +'ContentType', +'CreateFeedRequest', +'DeleteFeedRequest', +'Feed', +'FeedOutputConfig', +'GcsDestination', +'GetFeedRequest', +'ListFeedsRequest', +'ListFeedsResponse', +'OutputConfig', +'PubsubDestination', +'Resource', +'TemporalAsset', +'TimeWindow', +'UpdateFeedRequest', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json new file mode 100644 index 00000000..792efcd7 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json @@ -0,0 +1,103 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1p2beta1", + "protoPackage": "google.cloud.asset.v1p2beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + }, + "rest": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py new file mode 100644 index 00000000..89a37dc9 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py new file mode 100644 index 00000000..542f923f --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient + +__all__ = ( + 'AssetServiceClient', + 'AssetServiceAsyncClient', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..3593d3e1 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py @@ -0,0 +1,751 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.asset_v1p2beta1 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.cloud.asset_v1p2beta1.types import asset_service +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + feed_path = staticmethod(AssetServiceClient.feed_path) + parse_feed_path = staticmethod(AssetServiceClient.parse_feed_path) + common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AssetServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AssetServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AssetServiceClient.common_project_path) + parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) + common_location_path = staticmethod(AssetServiceClient.common_location_path) + parse_common_location_path = staticmethod(AssetServiceClient.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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_feed(self, + request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + .. 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 asset_v1p2beta1 + + async def sample_create_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = await client.create_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1p2beta1.types.CreateFeedRequest, dict]]): + The request object. Create asset feed request. + parent (:class:`str`): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id")", or + a project number (such as + "projects/12345"). + + 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.asset_v1p2beta1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + # 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 = asset_service.CreateFeedRequest(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.create_feed, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_feed(self, + request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + .. 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 asset_v1p2beta1 + + async def sample_get_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = await client.get_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1p2beta1.types.GetFeedRequest, dict]]): + The request object. Get asset feed request. + name (:class:`str`): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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.asset_v1p2beta1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + # 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 = asset_service.GetFeedRequest(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_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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_feeds(self, + request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + .. 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 asset_v1p2beta1 + + async def sample_list_feeds(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_feeds(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1p2beta1.types.ListFeedsRequest, dict]]): + The request object. List asset feeds request. + parent (:class:`str`): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-id"). + + 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.asset_v1p2beta1.types.ListFeedsResponse: + + """ + # 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 = asset_service.ListFeedsRequest(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_feeds, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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_feed(self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + .. 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 asset_v1p2beta1 + + async def sample_update_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = await client.update_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1p2beta1.types.UpdateFeedRequest, dict]]): + The request object. Update asset feed request. + feed (:class:`google.cloud.asset_v1p2beta1.types.Feed`): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + + This corresponds to the ``feed`` 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.asset_v1p2beta1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + # 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([feed]) + 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 = asset_service.UpdateFeedRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if feed is not None: + request.feed = feed + + # 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_feed, + 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(( + ("feed.name", request.feed.name), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_feed(self, + request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. + + .. 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 asset_v1p2beta1 + + async def sample_delete_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + await client.delete_feed(request=request) + + Args: + request (Optional[Union[google.cloud.asset_v1p2beta1.types.DeleteFeedRequest, dict]]): + The request object. + name (:class:`str`): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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 = asset_service.DeleteFeedRequest(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_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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 __aenter__(self) -> "AssetServiceAsyncClient": + 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__ = ( + "AssetServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py new file mode 100644 index 00000000..b2d6a61a --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py @@ -0,0 +1,934 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.asset_v1p2beta1 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.cloud.asset_v1p2beta1.types import asset_service +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .transports.rest import AssetServiceRestTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService 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[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AssetServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AssetServiceTransport]: + """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 AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @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 = "cloudasset.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: + AssetServiceClient: 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: + AssetServiceClient: 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) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def feed_path(project: str,feed: str,) -> str: + """Returns a fully-qualified feed string.""" + return "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) + + @staticmethod + def parse_feed_path(path: str) -> Dict[str,str]: + """Parses a feed path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/feeds/(?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, AssetServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): + # transport is a AssetServiceTransport 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_feed(self, + request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + .. 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 asset_v1p2beta1 + + def sample_create_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = client.create_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1p2beta1.types.CreateFeedRequest, dict]): + The request object. Create asset feed request. + parent (str): + Required. The name of the + project/folder/organization where this + feed should be created in. It can only + be an organization number (such as + "organizations/123"), a folder number + (such as "folders/123"), a project ID + (such as "projects/my-project-id")", or + a project number (such as + "projects/12345"). + + 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.asset_v1p2beta1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + # 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 asset_service.CreateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.CreateFeedRequest): + request = asset_service.CreateFeedRequest(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.create_feed] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_feed(self, + request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + .. 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 asset_v1p2beta1 + + def sample_get_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = client.get_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1p2beta1.types.GetFeedRequest, dict]): + The request object. Get asset feed request. + name (str): + Required. The name of the Feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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.asset_v1p2beta1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + # 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 asset_service.GetFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.GetFeedRequest): + request = asset_service.GetFeedRequest(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_feed] + + # 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_feeds(self, + request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + .. 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 asset_v1p2beta1 + + def sample_list_feeds(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_feeds(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1p2beta1.types.ListFeedsRequest, dict]): + The request object. List asset feeds request. + parent (str): + Required. The parent + project/folder/organization whose feeds + are to be listed. It can only be using + project/folder/organization number (such + as "folders/12345")", or a project ID + (such as "projects/my-project-id"). + + 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.asset_v1p2beta1.types.ListFeedsResponse: + + """ + # 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 asset_service.ListFeedsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListFeedsRequest): + request = asset_service.ListFeedsRequest(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_feeds] + + # 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_feed(self, + request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, + *, + feed: Optional[asset_service.Feed] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + .. 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 asset_v1p2beta1 + + def sample_update_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = client.update_feed(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.asset_v1p2beta1.types.UpdateFeedRequest, dict]): + The request object. Update asset feed request. + feed (google.cloud.asset_v1p2beta1.types.Feed): + Required. The new values of feed details. It must match + an existing feed and the field ``name`` must be in the + format of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + + This corresponds to the ``feed`` 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.asset_v1p2beta1.types.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + # 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([feed]) + 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 asset_service.UpdateFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.UpdateFeedRequest): + request = asset_service.UpdateFeedRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if feed is not None: + request.feed = feed + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_feed] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("feed.name", request.feed.name), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_feed(self, + request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. + + .. 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 asset_v1p2beta1 + + def sample_delete_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + client.delete_feed(request=request) + + Args: + request (Union[google.cloud.asset_v1p2beta1.types.DeleteFeedRequest, dict]): + The request object. + name (str): + Required. The name of the feed and it must be in the + format of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + + 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 asset_service.DeleteFeedRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.DeleteFeedRequest): + request = asset_service.DeleteFeedRequest(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_feed] + + # 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) -> "AssetServiceClient": + 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() + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AssetServiceClient", +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..c34a5f8f --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .rest import AssetServiceRestTransport +from .rest import AssetServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AssetServiceRestTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', + 'AssetServiceRestTransport', + 'AssetServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..616011c6 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py @@ -0,0 +1,226 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.asset_v1p2beta1 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.cloud.asset_v1p2beta1.types import asset_service +from google.protobuf import empty_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudasset.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_feed: gapic_v1.method.wrap_method( + self.create_feed, + default_timeout=60.0, + client_info=client_info, + ), + self.get_feed: gapic_v1.method.wrap_method( + self.get_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_feeds: gapic_v1.method.wrap_method( + self.list_feeds, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_feed: gapic_v1.method.wrap_method( + self.update_feed, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_feed: gapic_v1.method.wrap_method( + self.delete_feed, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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 create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: + raise NotImplementedError() + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: + raise NotImplementedError() + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + Union[ + asset_service.ListFeedsResponse, + Awaitable[asset_service.ListFeedsResponse] + ]]: + raise NotImplementedError() + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + Union[ + asset_service.Feed, + Awaitable[asset_service.Feed] + ]]: + raise NotImplementedError() + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + Union[ + empty_pb2.Empty, + Awaitable[empty_pb2.Empty] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AssetServiceTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..cc2179d2 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,372 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.asset_v1p2beta1.types import asset_service +from google.protobuf import empty_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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 create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + asset_service.Feed]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + ~.Feed]: + 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_feed' not in self._stubs: + self._stubs['create_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/CreateFeed', + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['create_feed'] + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + asset_service.Feed]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + ~.Feed]: + 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_feed' not in self._stubs: + self._stubs['get_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/GetFeed', + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['get_feed'] + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + asset_service.ListFeedsResponse]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + ~.ListFeedsResponse]: + 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_feeds' not in self._stubs: + self._stubs['list_feeds'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/ListFeeds', + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs['list_feeds'] + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + asset_service.Feed]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + ~.Feed]: + 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_feed' not in self._stubs: + self._stubs['update_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed', + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['update_feed'] + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + empty_pb2.Empty]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + ~.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_feed' not in self._stubs: + self._stubs['delete_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed', + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_feed'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AssetServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2060aa07 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,371 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.asset_v1p2beta1.types import asset_service +from google.protobuf import empty_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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 create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + Awaitable[asset_service.Feed]]: + r"""Return a callable for the create feed method over gRPC. + + Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Returns: + Callable[[~.CreateFeedRequest], + Awaitable[~.Feed]]: + 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_feed' not in self._stubs: + self._stubs['create_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/CreateFeed', + request_serializer=asset_service.CreateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['create_feed'] + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + Awaitable[asset_service.Feed]]: + r"""Return a callable for the get feed method over gRPC. + + Gets details about an asset feed. + + Returns: + Callable[[~.GetFeedRequest], + Awaitable[~.Feed]]: + 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_feed' not in self._stubs: + self._stubs['get_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/GetFeed', + request_serializer=asset_service.GetFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['get_feed'] + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + Awaitable[asset_service.ListFeedsResponse]]: + r"""Return a callable for the list feeds method over gRPC. + + Lists all asset feeds in a parent + project/folder/organization. + + Returns: + Callable[[~.ListFeedsRequest], + Awaitable[~.ListFeedsResponse]]: + 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_feeds' not in self._stubs: + self._stubs['list_feeds'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/ListFeeds', + request_serializer=asset_service.ListFeedsRequest.serialize, + response_deserializer=asset_service.ListFeedsResponse.deserialize, + ) + return self._stubs['list_feeds'] + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + Awaitable[asset_service.Feed]]: + r"""Return a callable for the update feed method over gRPC. + + Updates an asset feed configuration. + + Returns: + Callable[[~.UpdateFeedRequest], + Awaitable[~.Feed]]: + 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_feed' not in self._stubs: + self._stubs['update_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed', + request_serializer=asset_service.UpdateFeedRequest.serialize, + response_deserializer=asset_service.Feed.deserialize, + ) + return self._stubs['update_feed'] + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete feed method over gRPC. + + Deletes an asset feed. + + Returns: + Callable[[~.DeleteFeedRequest], + 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_feed' not in self._stubs: + self._stubs['delete_feed'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed', + request_serializer=asset_service.DeleteFeedRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs['delete_feed'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py new file mode 100644 index 00000000..b4ad28de --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py @@ -0,0 +1,747 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +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 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.asset_v1p2beta1.types import asset_service +from google.protobuf import empty_pb2 # type: ignore + +from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: + """Interceptor for AssetService. + + 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 AssetServiceRestTransport. + + .. code-block:: python + class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): + def pre_create_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_feed(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_feed(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_feeds(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_feeds(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_feed(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_feed(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) + client = AssetServiceClient(transport=transport) + + + """ + def pre_create_feed(self, request: asset_service.CreateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.CreateFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_create_feed(self, response: asset_service.Feed) -> asset_service.Feed: + """Post-rpc interceptor for create_feed + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_delete_feed(self, request: asset_service.DeleteFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.DeleteFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def pre_get_feed(self, request: asset_service.GetFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.GetFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_get_feed(self, response: asset_service.Feed) -> asset_service.Feed: + """Post-rpc interceptor for get_feed + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_list_feeds(self, request: asset_service.ListFeedsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListFeedsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_feeds + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_list_feeds(self, response: asset_service.ListFeedsResponse) -> asset_service.ListFeedsResponse: + """Post-rpc interceptor for list_feeds + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + def pre_update_feed(self, request: asset_service.UpdateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.UpdateFeedRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_feed + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_update_feed(self, response: asset_service.Feed) -> asset_service.Feed: + """Post-rpc interceptor for update_feed + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AssetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AssetServiceRestInterceptor + + +class AssetServiceRestTransport(AssetServiceTransport): + """REST backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateFeed(AssetServiceRestStub): + def __hash__(self): + return hash("CreateFeed") + + __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: asset_service.CreateFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.Feed: + r"""Call the create feed method over HTTP. + + Args: + request (~.asset_service.CreateFeedRequest): + The request object. Create asset feed request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1p2beta1/{parent=*/*}/feeds', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_create_feed(request, metadata) + pb_request = asset_service.CreateFeedRequest.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 = asset_service.Feed() + pb_resp = asset_service.Feed.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_feed(resp) + return resp + + class _DeleteFeed(AssetServiceRestStub): + def __hash__(self): + return hash("DeleteFeed") + + __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: asset_service.DeleteFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ): + r"""Call the delete feed method over HTTP. + + Args: + request (~.asset_service.DeleteFeedRequest): + The request object. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'delete', + 'uri': '/v1p2beta1/{name=*/*/feeds/*}', + }, + ] + request, metadata = self._interceptor.pre_delete_feed(request, metadata) + pb_request = asset_service.DeleteFeedRequest.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 _GetFeed(AssetServiceRestStub): + def __hash__(self): + return hash("GetFeed") + + __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: asset_service.GetFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.Feed: + r"""Call the get feed method over HTTP. + + Args: + request (~.asset_service.GetFeedRequest): + The request object. Get asset feed request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p2beta1/{name=*/*/feeds/*}', + }, + ] + request, metadata = self._interceptor.pre_get_feed(request, metadata) + pb_request = asset_service.GetFeedRequest.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 = asset_service.Feed() + pb_resp = asset_service.Feed.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_feed(resp) + return resp + + class _ListFeeds(AssetServiceRestStub): + def __hash__(self): + return hash("ListFeeds") + + __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: asset_service.ListFeedsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.ListFeedsResponse: + r"""Call the list feeds method over HTTP. + + Args: + request (~.asset_service.ListFeedsRequest): + The request object. List asset feeds request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListFeedsResponse: + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p2beta1/{parent=*/*}/feeds', + }, + ] + request, metadata = self._interceptor.pre_list_feeds(request, metadata) + pb_request = asset_service.ListFeedsRequest.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 = asset_service.ListFeedsResponse() + pb_resp = asset_service.ListFeedsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_feeds(resp) + return resp + + class _UpdateFeed(AssetServiceRestStub): + def __hash__(self): + return hash("UpdateFeed") + + __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: asset_service.UpdateFeedRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.Feed: + r"""Call the update feed method over HTTP. + + Args: + request (~.asset_service.UpdateFeedRequest): + The request object. Update asset feed request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.Feed: + An asset feed used to export asset + updates to a destinations. An asset feed + filter controls what updates are + exported. The asset feed must be created + within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1p2beta1/{feed.name=*/*/feeds/*}', + 'body': '*', + }, + ] + request, metadata = self._interceptor.pre_update_feed(request, metadata) + pb_request = asset_service.UpdateFeedRequest.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 = asset_service.Feed() + pb_resp = asset_service.Feed.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_feed(resp) + return resp + + @property + def create_feed(self) -> Callable[ + [asset_service.CreateFeedRequest], + asset_service.Feed]: + # 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._CreateFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_feed(self) -> Callable[ + [asset_service.DeleteFeedRequest], + 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._DeleteFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_feed(self) -> Callable[ + [asset_service.GetFeedRequest], + asset_service.Feed]: + # 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._GetFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_feeds(self) -> Callable[ + [asset_service.ListFeedsRequest], + asset_service.ListFeedsResponse]: + # 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._ListFeeds(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_feed(self) -> Callable[ + [asset_service.UpdateFeedRequest], + asset_service.Feed]: + # 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._UpdateFeed(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AssetServiceRestTransport', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py new file mode 100644 index 00000000..960dd3d0 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .asset_service import ( + CreateFeedRequest, + DeleteFeedRequest, + Feed, + FeedOutputConfig, + GcsDestination, + GetFeedRequest, + ListFeedsRequest, + ListFeedsResponse, + OutputConfig, + PubsubDestination, + UpdateFeedRequest, + ContentType, +) +from .assets import ( + Asset, + Resource, + TemporalAsset, + TimeWindow, +) + +__all__ = ( + 'CreateFeedRequest', + 'DeleteFeedRequest', + 'Feed', + 'FeedOutputConfig', + 'GcsDestination', + 'GetFeedRequest', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'OutputConfig', + 'PubsubDestination', + 'UpdateFeedRequest', + 'ContentType', + 'Asset', + 'Resource', + 'TemporalAsset', + 'TimeWindow', +) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py new file mode 100644 index 00000000..56374f63 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py @@ -0,0 +1,346 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.protobuf import field_mask_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p2beta1', + manifest={ + 'ContentType', + 'CreateFeedRequest', + 'GetFeedRequest', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'UpdateFeedRequest', + 'DeleteFeedRequest', + 'OutputConfig', + 'GcsDestination', + 'PubsubDestination', + 'FeedOutputConfig', + 'Feed', + }, +) + + +class ContentType(proto.Enum): + r"""Asset content type. + + Values: + CONTENT_TYPE_UNSPECIFIED (0): + Unspecified content type. + RESOURCE (1): + Resource metadata. + IAM_POLICY (2): + The actual IAM policy set on a resource. + """ + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + + +class CreateFeedRequest(proto.Message): + r"""Create asset feed request. + + Attributes: + parent (str): + Required. The name of the + project/folder/organization where this feed + should be created in. It can only be an + organization number (such as + "organizations/123"), a folder number (such as + "folders/123"), a project ID (such as + "projects/my-project-id")", or a project number + (such as "projects/12345"). + feed_id (str): + Required. This is the client-assigned asset + feed identifier and it needs to be unique under + a specific parent project/folder/organization. + feed (google.cloud.asset_v1p2beta1.types.Feed): + Required. The feed details. The field ``name`` must be empty + and it will be generated in the format of: + projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + feed_id: str = proto.Field( + proto.STRING, + number=2, + ) + feed: 'Feed' = proto.Field( + proto.MESSAGE, + number=3, + message='Feed', + ) + + +class GetFeedRequest(proto.Message): + r"""Get asset feed request. + + Attributes: + name (str): + Required. The name of the Feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFeedsRequest(proto.Message): + r"""List asset feeds request. + + Attributes: + parent (str): + Required. The parent + project/folder/organization whose feeds are to + be listed. It can only be using + project/folder/organization number (such as + "folders/12345")", or a project ID (such as + "projects/my-project-id"). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFeedsResponse(proto.Message): + r""" + + Attributes: + feeds (MutableSequence[google.cloud.asset_v1p2beta1.types.Feed]): + A list of feeds. + """ + + feeds: MutableSequence['Feed'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='Feed', + ) + + +class UpdateFeedRequest(proto.Message): + r"""Update asset feed request. + + Attributes: + feed (google.cloud.asset_v1p2beta1.types.Feed): + Required. The new values of feed details. It must match an + existing feed and the field ``name`` must be in the format + of: projects/project_number/feeds/feed_id or + folders/folder_number/feeds/feed_id or + organizations/organization_number/feeds/feed_id. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Only updates the ``feed`` fields indicated by this + mask. The field mask must not be empty, and it must not + contain fields that are immutable or only set by the server. + """ + + feed: 'Feed' = proto.Field( + proto.MESSAGE, + number=1, + message='Feed', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteFeedRequest(proto.Message): + r""" + + Attributes: + name (str): + Required. The name of the feed and it must be in the format + of: projects/project_number/feeds/feed_id + folders/folder_number/feeds/feed_id + organizations/organization_number/feeds/feed_id + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class OutputConfig(proto.Message): + r"""Output configuration for export assets destination. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_destination (google.cloud.asset_v1p2beta1.types.GcsDestination): + Destination on Cloud Storage. + + This field is a member of `oneof`_ ``destination``. + """ + + gcs_destination: 'GcsDestination' = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + + +class GcsDestination(proto.Message): + r"""A Cloud Storage location. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + The uri of the Cloud Storage object. It's the same uri that + is used by gsutil. For example: + "gs://bucket_name/object_name". See `Viewing and Editing + Object + Metadata `__ + for more information. + + This field is a member of `oneof`_ ``object_uri``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + oneof='object_uri', + ) + + +class PubsubDestination(proto.Message): + r"""A Cloud Pubsub destination. + + Attributes: + topic (str): + The name of the Cloud Pub/Sub topic to publish to. For + example: ``projects/PROJECT_ID/topics/TOPIC_ID``. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + + +class FeedOutputConfig(proto.Message): + r"""Output configuration for asset feed destination. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + pubsub_destination (google.cloud.asset_v1p2beta1.types.PubsubDestination): + Destination on Cloud Pubsub. + + This field is a member of `oneof`_ ``destination``. + """ + + pubsub_destination: 'PubsubDestination' = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='PubsubDestination', + ) + + +class Feed(proto.Message): + r"""An asset feed used to export asset updates to a destinations. + An asset feed filter controls what updates are exported. The + asset feed must be created within a project, organization, or + folder. Supported destinations are: + + Cloud Pub/Sub topics. + + Attributes: + name (str): + Required. The format will be + projects/{project_number}/feeds/{client-assigned_feed_identifier} + or + folders/{folder_number}/feeds/{client-assigned_feed_identifier} + or + organizations/{organization_number}/feeds/{client-assigned_feed_identifier} + + The client-assigned feed identifier must be unique within + the parent project/folder/organization. + asset_names (MutableSequence[str]): + A list of the full names of the assets to receive updates. + You must specify either or both of asset_names and + asset_types. Only asset updates matching specified + asset_names and asset_types are exported to the feed. For + example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more info. + asset_types (MutableSequence[str]): + A list of types of the assets to receive updates. You must + specify either or both of asset_names and asset_types. Only + asset updates matching specified asset_names and asset_types + are exported to the feed. For example: + "compute.googleapis.com/Disk" See `Introduction to Cloud + Asset + Inventory `__ + for all supported asset types. + content_type (google.cloud.asset_v1p2beta1.types.ContentType): + Asset content type. If not specified, no + content but the asset name and type will be + returned. + feed_output_config (google.cloud.asset_v1p2beta1.types.FeedOutputConfig): + Required. Feed output configuration defining + where the asset updates are published to. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type: 'ContentType' = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + feed_output_config: 'FeedOutputConfig' = proto.Field( + proto.MESSAGE, + number=5, + message='FeedOutputConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py new file mode 100644 index 00000000..99d30e80 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py @@ -0,0 +1,218 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p2beta1', + manifest={ + 'TemporalAsset', + 'TimeWindow', + 'Asset', + 'Resource', + }, +) + + +class TemporalAsset(proto.Message): + r"""Temporal asset. In addition to the asset, the temporal asset + includes the status of the asset and valid from and to time of + it. + + Attributes: + window (google.cloud.asset_v1p2beta1.types.TimeWindow): + The time window when the asset data and state + was observed. + deleted (bool): + If the asset is deleted or not. + asset (google.cloud.asset_v1p2beta1.types.Asset): + Asset. + """ + + window: 'TimeWindow' = proto.Field( + proto.MESSAGE, + number=1, + message='TimeWindow', + ) + deleted: bool = proto.Field( + proto.BOOL, + number=2, + ) + asset: 'Asset' = proto.Field( + proto.MESSAGE, + number=3, + message='Asset', + ) + + +class TimeWindow(proto.Message): + r"""A time window of (start_time, end_time]. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of the time window (exclusive). + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the time window (inclusive). + Current timestamp if not specified. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class Asset(proto.Message): + r"""Cloud asset. This includes all Google Cloud Platform + resources, Cloud IAM policies, and other non-GCP assets. + + Attributes: + name (str): + The full name of the asset. For example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. + See `Resource + Names `__ + for more information. + asset_type (str): + Type of the asset. Example: + "compute.googleapis.com/Disk". + resource (google.cloud.asset_v1p2beta1.types.Resource): + Representation of the resource. + iam_policy (google.iam.v1.policy_pb2.Policy): + Representation of the actual Cloud IAM policy + set on a cloud resource. For each resource, + there must be at most one Cloud IAM policy set + on it. + ancestors (MutableSequence[str]): + Asset's ancestry path in Cloud Resource Manager (CRM) + hierarchy, represented as a list of relative resource names. + Ancestry path starts with the closest CRM ancestor and ends + at root. If the asset is a CRM project/folder/organization, + this starts from the asset itself. + + Example: ["projects/123456789", "folders/5432", + "organizations/1234"] + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource: 'Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='Resource', + ) + iam_policy: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + ancestors: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class Resource(proto.Message): + r"""Representation of a cloud resource. + + Attributes: + version (str): + The API version. Example: "v1". + discovery_document_uri (str): + The URL of the discovery document containing the resource's + JSON schema. For example: + ``"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"``. + It will be left unspecified for resources without a + discovery-based API, such as Cloud Bigtable. + discovery_name (str): + The JSON schema name listed in the discovery + document. Example: "Project". It will be left + unspecified for resources (such as Cloud + Bigtable) without a discovery-based API. + resource_url (str): + The REST URL for accessing the resource. An HTTP GET + operation using this URL returns the resource itself. + Example: + ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123``. + It will be left unspecified for resources without a REST + API. + parent (str): + The full name of the immediate parent of this resource. See + `Resource + Names `__ + for more information. + + For GCP assets, it is the parent resource defined in the + `Cloud IAM policy + hierarchy `__. + For example: + ``"//cloudresourcemanager.googleapis.com/projects/my_project_123"``. + + For third-party assets, it is up to the users to define. + data (google.protobuf.struct_pb2.Struct): + The content of the resource, in which some + sensitive fields are scrubbed away and may not + be present. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + discovery_document_uri: str = proto.Field( + proto.STRING, + number=2, + ) + discovery_name: str = proto.Field( + proto.STRING, + number=3, + ) + resource_url: str = proto.Field( + proto.STRING, + number=4, + ) + parent: str = proto.Field( + proto.STRING, + number=5, + ) + data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p2beta1/mypy.ini b/owl-bot-staging/v1p2beta1/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1p2beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1p2beta1/noxfile.py b/owl-bot-staging/v1p2beta1/noxfile.py new file mode 100644 index 00000000..fb73a1cc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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/asset_v1p2beta1/', + '--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==7.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/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py new file mode 100644 index 00000000..f67a4091 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_CreateFeed_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 asset_v1p2beta1 + + +async def sample_create_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = await client.create_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_CreateFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py new file mode 100644 index 00000000..81a02f1e --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_CreateFeed_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 asset_v1p2beta1 + + +def sample_create_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.CreateFeedRequest( + parent="parent_value", + feed_id="feed_id_value", + feed=feed, + ) + + # Make the request + response = client.create_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_CreateFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py new file mode 100644 index 00000000..6cdb9735 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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 asset_v1p2beta1 + + +async def sample_delete_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + await client.delete_feed(request=request) + + +# [END cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py new file mode 100644 index 00000000..344ec815 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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 asset_v1p2beta1 + + +def sample_delete_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.DeleteFeedRequest( + name="name_value", + ) + + # Make the request + client.delete_feed(request=request) + + +# [END cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py new file mode 100644 index 00000000..fe72e7dd --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_GetFeed_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 asset_v1p2beta1 + + +async def sample_get_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = await client.get_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_GetFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py new file mode 100644 index 00000000..d195101d --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_GetFeed_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 asset_v1p2beta1 + + +def sample_get_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.GetFeedRequest( + name="name_value", + ) + + # Make the request + response = client.get_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_GetFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py new file mode 100644 index 00000000..075192eb --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFeeds +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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 asset_v1p2beta1 + + +async def sample_list_feeds(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = await client.list_feeds(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_ListFeeds_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py new file mode 100644 index 00000000..75cf95b5 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListFeeds +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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 asset_v1p2beta1 + + +def sample_list_feeds(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p2beta1.ListFeedsRequest( + parent="parent_value", + ) + + # Make the request + response = client.list_feeds(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_ListFeeds_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py new file mode 100644 index 00000000..9dcdad41 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_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 asset_v1p2beta1 + + +async def sample_update_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = await client.update_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py new file mode 100644 index 00000000..697a6e4b --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateFeed +# 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-asset + + +# [START cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_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 asset_v1p2beta1 + + +def sample_update_feed(): + # Create a client + client = asset_v1p2beta1.AssetServiceClient() + + # Initialize request argument(s) + feed = asset_v1p2beta1.Feed() + feed.name = "name_value" + + request = asset_v1p2beta1.UpdateFeedRequest( + feed=feed, + ) + + # Make the request + response = client.update_feed(request=request) + + # Handle the response + print(response) + +# [END cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json b/owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json new file mode 100644 index 00000000..38eaede8 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json @@ -0,0 +1,814 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.asset.v1p2beta1", + "version": "v1p2beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-asset", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.create_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.CreateFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "CreateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.CreateFeedRequest" + }, + { + "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.asset_v1p2beta1.types.Feed", + "shortName": "create_feed" + }, + "description": "Sample for CreateFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_CreateFeed_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.create_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.CreateFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "CreateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.CreateFeedRequest" + }, + { + "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.asset_v1p2beta1.types.Feed", + "shortName": "create_feed" + }, + "description": "Sample for CreateFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_CreateFeed_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.delete_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.DeleteFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "DeleteFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.DeleteFeedRequest" + }, + { + "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_feed" + }, + "description": "Sample for DeleteFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.delete_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.DeleteFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "DeleteFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.DeleteFeedRequest" + }, + { + "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_feed" + }, + "description": "Sample for DeleteFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.get_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.GetFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "GetFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.GetFeedRequest" + }, + { + "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.asset_v1p2beta1.types.Feed", + "shortName": "get_feed" + }, + "description": "Sample for GetFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_GetFeed_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": "cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.get_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.GetFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "GetFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.GetFeedRequest" + }, + { + "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.asset_v1p2beta1.types.Feed", + "shortName": "get_feed" + }, + "description": "Sample for GetFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_GetFeed_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": "cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.list_feeds", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.ListFeeds", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListFeeds" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.ListFeedsRequest" + }, + { + "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.asset_v1p2beta1.types.ListFeedsResponse", + "shortName": "list_feeds" + }, + "description": "Sample for ListFeeds", + "file": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.list_feeds", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.ListFeeds", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListFeeds" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.ListFeedsRequest" + }, + { + "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.asset_v1p2beta1.types.ListFeedsResponse", + "shortName": "list_feeds" + }, + "description": "Sample for ListFeeds", + "file": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.update_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.UpdateFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "UpdateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.UpdateFeedRequest" + }, + { + "name": "feed", + "type": "google.cloud.asset_v1p2beta1.types.Feed" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1p2beta1.types.Feed", + "shortName": "update_feed" + }, + "description": "Sample for UpdateFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.update_feed", + "method": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService.UpdateFeed", + "service": { + "fullName": "google.cloud.asset.v1p2beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "UpdateFeed" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p2beta1.types.UpdateFeedRequest" + }, + { + "name": "feed", + "type": "google.cloud.asset_v1p2beta1.types.Feed" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.asset_v1p2beta1.types.Feed", + "shortName": "update_feed" + }, + "description": "Sample for UpdateFeed", + "file": "cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py b/owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py new file mode 100644 index 00000000..f6174e16 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py @@ -0,0 +1,180 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'create_feed': ('parent', 'feed_id', 'feed', ), + 'delete_feed': ('name', ), + 'get_feed': ('name', ), + 'list_feeds': ('parent', ), + 'update_feed': ('feed', 'update_mask', ), + } + + 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=assetCallTransformer(), +): + """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 asset 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/v1p2beta1/setup.py b/owl-bot-staging/v1p2beta1/setup.py new file mode 100644 index 00000000..166120b0 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-asset' + + +description = "Google Cloud Asset API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/asset/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-asset" + +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/v1p2beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.10.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.11.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.12.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.7.txt new file mode 100644 index 00000000..2beecf99 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.8.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.9.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/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/v1p2beta1/tests/__init__.py b/owl-bot-staging/v1p2beta1/tests/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py new file mode 100644 index 00000000..c9053953 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -0,0 +1,3600 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 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.asset_v1p2beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p2beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p2beta1.services.asset_service import transports +from google.cloud.asset_v1p2beta1.types import asset_service +from google.oauth2 import service_account +from google.protobuf import field_mask_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 AssetServiceClient._get_default_mtls_endpoint(None) is None + assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceRestTransport, + ] + assert transport in available_transports + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_asset_service_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", [ + AssetServiceClient, AssetServiceAsyncClient +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), +]) +def test_asset_service_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_asset_service_client_client_options_from_dict(): + with mock.patch('google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.CreateFeedRequest, + dict, +]) +def test_create_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + ) + response = client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_create_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.create_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateFeedRequest() + +@pytest.mark.asyncio +async def test_create_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.CreateFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + )) + response = await client.create_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.CreateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +@pytest.mark.asyncio +async def test_create_feed_async_from_dict(): + await test_create_feed_async(request_type=dict) + + +def test_create_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + call.return_value = asset_service.Feed() + client.create_feed(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_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.CreateFeedRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + await client.create_feed(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_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_feed( + 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_create_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.CreateFeedRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_create_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_feed( + 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_create_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.CreateFeedRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.GetFeedRequest, + dict, +]) +def test_get_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + ) + response = client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_get_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.get_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetFeedRequest() + +@pytest.mark.asyncio +async def test_get_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.GetFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + )) + response = await client.get_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.GetFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +@pytest.mark.asyncio +async def test_get_feed_async_from_dict(): + await test_get_feed_async(request_type=dict) + + +def test_get_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + call.return_value = asset_service.Feed() + client.get_feed(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_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.GetFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + await client.get_feed(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_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_feed( + 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_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.GetFeedRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_feed( + 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_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.GetFeedRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListFeedsRequest, + dict, +]) +def test_list_feeds(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse( + ) + response = client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListFeedsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_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 = AssetServiceClient( + 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_feeds), + '__call__') as call: + client.list_feeds() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListFeedsRequest() + +@pytest.mark.asyncio +async def test_list_feeds_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListFeedsRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse( + )) + response = await client.list_feeds(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListFeedsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +@pytest.mark.asyncio +async def test_list_feeds_async_from_dict(): + await test_list_feeds_async(request_type=dict) + + +def test_list_feeds_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + call.return_value = asset_service.ListFeedsResponse() + client.list_feeds(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_feeds_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListFeedsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) + await client.list_feeds(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_feeds_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_feeds( + 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_feeds_flattened_error(): + client = AssetServiceClient( + 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_feeds( + asset_service.ListFeedsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_feeds_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_feeds), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListFeedsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_feeds( + 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_feeds_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feeds( + asset_service.ListFeedsRequest(), + parent='parent_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.UpdateFeedRequest, + dict, +]) +def test_update_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + ) + response = client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_update_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.update_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateFeedRequest() + +@pytest.mark.asyncio +async def test_update_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.UpdateFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + )) + response = await client.update_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.UpdateFeedRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +@pytest.mark.asyncio +async def test_update_feed_async_from_dict(): + await test_update_feed_async(request_type=dict) + + +def test_update_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + + request.feed.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + call.return_value = asset_service.Feed() + client.update_feed(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', + 'feed.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.UpdateFeedRequest() + + request.feed.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + await client.update_feed(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', + 'feed.name=name_value', + ) in kw['metadata'] + + +def test_update_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_feed( + feed=asset_service.Feed(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].feed + mock_val = asset_service.Feed(name='name_value') + assert arg == mock_val + + +def test_update_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_update_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.Feed() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_feed( + feed=asset_service.Feed(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].feed + mock_val = asset_service.Feed(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.DeleteFeedRequest, + dict, +]) +def test_delete_feed(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteFeedRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_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 = AssetServiceClient( + 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_feed), + '__call__') as call: + client.delete_feed() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteFeedRequest() + +@pytest.mark.asyncio +async def test_delete_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.DeleteFeedRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_feed), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_feed(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.DeleteFeedRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_feed_async_from_dict(): + await test_delete_feed_async(request_type=dict) + + +def test_delete_feed_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__call__') as call: + call.return_value = None + client.delete_feed(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_feed_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.DeleteFeedRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_feed(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_feed_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__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_feed( + 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_feed_flattened_error(): + client = AssetServiceClient( + 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_feed( + asset_service.DeleteFeedRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_delete_feed_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_feed), + '__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_feed( + 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_feed_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_feed( + asset_service.DeleteFeedRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.CreateFeedRequest, + dict, +]) +def test_create_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_feed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_create_feed_rest_required_fields(request_type=asset_service.CreateFeedRequest): + transport_class = transports.AssetServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["feed_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()).create_feed._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["feedId"] = 'feed_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_feed._get_unset_required_fields(jsonified_request) + 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 "feedId" in jsonified_request + assert jsonified_request["feedId"] == 'feed_id_value' + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.Feed() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "feedId", "feed", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_create_feed") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_create_feed") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.CreateFeedRequest.pb(asset_service.CreateFeedRequest()) + 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 = asset_service.Feed.to_json(asset_service.Feed()) + + request = asset_service.CreateFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.Feed() + + client.create_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.CreateFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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.create_feed(request) + + +def test_create_feed_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.Feed() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/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 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_feed(**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/v1p2beta1/{parent=*/*}/feeds" % client.transport._host, args[1]) + + +def test_create_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.CreateFeedRequest(), + parent='parent_value', + ) + + +def test_create_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.GetFeedRequest, + dict, +]) +def test_get_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.get_feed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_get_feed_rest_required_fields(request_type=asset_service.GetFeedRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feed._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_feed._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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.Feed() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.get_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_get_feed") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_get_feed") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.GetFeedRequest.pb(asset_service.GetFeedRequest()) + 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 = asset_service.Feed.to_json(asset_service.Feed()) + + request = asset_service.GetFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.Feed() + + client.get_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.GetFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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_feed(request) + + +def test_get_feed_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.Feed() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'sample1/sample2/feeds/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 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.get_feed(**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/v1p2beta1/{name=*/*/feeds/*}" % client.transport._host, args[1]) + + +def test_get_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.GetFeedRequest(), + name='name_value', + ) + + +def test_get_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListFeedsRequest, + dict, +]) +def test_list_feeds_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.ListFeedsResponse( + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_feeds(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.ListFeedsResponse) + + +def test_list_feeds_rest_required_fields(request_type=asset_service.ListFeedsRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feeds._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_feeds._get_unset_required_fields(jsonified_request) + 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.ListFeedsResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_feeds(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_feeds_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_feeds._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_feeds_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_feeds") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_feeds") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.ListFeedsRequest.pb(asset_service.ListFeedsRequest()) + 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 = asset_service.ListFeedsResponse.to_json(asset_service.ListFeedsResponse()) + + request = asset_service.ListFeedsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.ListFeedsResponse() + + client.list_feeds(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_feeds_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListFeedsRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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_feeds(request) + + +def test_list_feeds_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.ListFeedsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/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 + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_feeds(**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/v1p2beta1/{parent=*/*}/feeds" % client.transport._host, args[1]) + + +def test_list_feeds_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feeds( + asset_service.ListFeedsRequest(), + parent='parent_value', + ) + + +def test_list_feeds_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.UpdateFeedRequest, + dict, +]) +def test_update_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'feed': {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( + name='name_value', + asset_names=['asset_names_value'], + asset_types=['asset_types_value'], + content_type=asset_service.ContentType.RESOURCE, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_feed(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, asset_service.Feed) + assert response.name == 'name_value' + assert response.asset_names == ['asset_names_value'] + assert response.asset_types == ['asset_types_value'] + assert response.content_type == asset_service.ContentType.RESOURCE + + +def test_update_feed_rest_required_fields(request_type=asset_service.UpdateFeedRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feed._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_feed._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.Feed() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("feed", "updateMask", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_update_feed") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_update_feed") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.UpdateFeedRequest.pb(asset_service.UpdateFeedRequest()) + 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 = asset_service.Feed.to_json(asset_service.Feed()) + + request = asset_service.UpdateFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.Feed() + + client.update_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.UpdateFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'feed': {'name': 'sample1/sample2/feeds/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.update_feed(request) + + +def test_update_feed_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.Feed() + + # get arguments that satisfy an http rule for this method + sample_request = {'feed': {'name': 'sample1/sample2/feeds/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + feed=asset_service.Feed(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_feed(**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/v1p2beta1/{feed.name=*/*/feeds/*}" % client.transport._host, args[1]) + + +def test_update_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.UpdateFeedRequest(), + feed=asset_service.Feed(name='name_value'), + ) + + +def test_update_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.DeleteFeedRequest, + dict, +]) +def test_delete_feed_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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_feed(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_feed_rest_required_fields(request_type=asset_service.DeleteFeedRequest): + transport_class = transports.AssetServiceRestTransport + + 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_feed._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_feed._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 = AssetServiceClient( + 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_feed(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_delete_feed_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.delete_feed._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_feed_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "pre_delete_feed") as pre: + pre.assert_not_called() + pb_message = asset_service.DeleteFeedRequest.pb(asset_service.DeleteFeedRequest()) + 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 = asset_service.DeleteFeedRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + + +def test_delete_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.DeleteFeedRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'sample1/sample2/feeds/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_feed(request) + + +def test_delete_feed_rest_flattened(): + client = AssetServiceClient( + 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': 'sample1/sample2/feeds/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_feed(**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/v1p2beta1/{name=*/*/feeds/*}" % client.transport._host, args[1]) + + +def test_delete_feed_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_feed( + asset_service.DeleteFeedRequest(), + name='name_value', + ) + + +def test_delete_feed_rest_error(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest' + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AssetServiceClient( + 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 = AssetServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, +]) +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 = AssetServiceClient.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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AssetServiceGrpcTransport, + ) + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_feed', + 'get_feed', + 'list_feeds', + 'update_feed', + 'delete_feed', + ) + 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_asset_service_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.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + 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_asset_service_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.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport() + adc.assert_called_once() + + +def test_asset_service_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) + AssetServiceClient() + 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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( + 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_asset_service_host_no_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_asset_service_host_with_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_asset_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AssetServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AssetServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_feed._session + session2 = client2.transport.create_feed._session + assert session1 != session2 + session1 = client1.transport.get_feed._session + session2 = client2.transport.get_feed._session + assert session1 != session2 + session1 = client1.transport.list_feeds._session + session2 = client2.transport.list_feeds._session + assert session1 != session2 + session1 = client1.transport.update_feed._session + session2 = client2.transport.update_feed._session + assert session1 != session2 + session1 = client1.transport.delete_feed._session + session2 = client2.transport.delete_feed._session + assert session1 != session2 +def test_asset_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcTransport( + 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_asset_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcAsyncIOTransport( + 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_feed_path(): + project = "squid" + feed = "clam" + expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) + actual = AssetServiceClient.feed_path(project, feed) + assert expected == actual + + +def test_parse_feed_path(): + expected = { + "project": "whelk", + "feed": "octopus", + } + path = AssetServiceClient.feed_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_feed_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AssetServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = AssetServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format(folder=folder, ) + actual = AssetServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = AssetServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AssetServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = AssetServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format(project=project, ) + actual = AssetServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = AssetServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AssetServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = AssetServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( + 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_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AssetServiceClient( + 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 = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), +]) +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/v1p5beta1/.coveragerc b/owl-bot-staging/v1p5beta1/.coveragerc new file mode 100644 index 00000000..801f6d8a --- /dev/null +++ b/owl-bot-staging/v1p5beta1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py + google/cloud/asset/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/v1p5beta1/.flake8 b/owl-bot-staging/v1p5beta1/.flake8 new file mode 100644 index 00000000..29227d4c --- /dev/null +++ b/owl-bot-staging/v1p5beta1/.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/v1p5beta1/MANIFEST.in b/owl-bot-staging/v1p5beta1/MANIFEST.in new file mode 100644 index 00000000..7000a398 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/asset *.py +recursive-include google/cloud/asset_v1p5beta1 *.py diff --git a/owl-bot-staging/v1p5beta1/README.rst b/owl-bot-staging/v1p5beta1/README.rst new file mode 100644 index 00000000..110d4086 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Asset 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 Asset 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/v1p5beta1/docs/_static/custom.css b/owl-bot-staging/v1p5beta1/docs/_static/custom.css new file mode 100644 index 00000000..06423be0 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst new file mode 100644 index 00000000..fa5fcb62 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst @@ -0,0 +1,10 @@ +AssetService +------------------------------ + +.. automodule:: google.cloud.asset_v1p5beta1.services.asset_service + :members: + :inherited-members: + +.. automodule:: google.cloud.asset_v1p5beta1.services.asset_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst new file mode 100644 index 00000000..9383f20c --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p5beta1 API +============================================= +.. toctree:: + :maxdepth: 2 + + asset_service diff --git a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst new file mode 100644 index 00000000..0d143122 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Asset v1p5beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p5beta1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/v1p5beta1/docs/conf.py b/owl-bot-staging/v1p5beta1/docs/conf.py new file mode 100644 index 00000000..b6b4f094 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-asset 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-asset" +copyright = u"2023, 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 = 'en' + +# 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-asset-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-asset.tex", + u"google-cloud-asset 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-asset", + u"Google Cloud Asset 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-asset", + u"google-cloud-asset Documentation", + author, + "google-cloud-asset", + "GAPIC library for Google Cloud Asset 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/v1p5beta1/docs/index.rst b/owl-bot-staging/v1p5beta1/docs/index.rst new file mode 100644 index 00000000..de7b35fd --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + asset_v1p5beta1/services + asset_v1p5beta1/types diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py new file mode 100644 index 00000000..7ecccc13 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.asset_v1p5beta1.services.asset_service.client import AssetServiceClient +from google.cloud.asset_v1p5beta1.services.asset_service.async_client import AssetServiceAsyncClient + +from google.cloud.asset_v1p5beta1.types.asset_service import ListAssetsRequest +from google.cloud.asset_v1p5beta1.types.asset_service import ListAssetsResponse +from google.cloud.asset_v1p5beta1.types.asset_service import ContentType +from google.cloud.asset_v1p5beta1.types.assets import Asset +from google.cloud.asset_v1p5beta1.types.assets import Resource + +__all__ = ('AssetServiceClient', + 'AssetServiceAsyncClient', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ContentType', + 'Asset', + 'Resource', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py new file mode 100644 index 00000000..70408635 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.cloud.asset_v1p5beta1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + +from .types.asset_service import ListAssetsRequest +from .types.asset_service import ListAssetsResponse +from .types.asset_service import ContentType +from .types.assets import Asset +from .types.assets import Resource + +__all__ = ( + 'AssetServiceAsyncClient', +'Asset', +'AssetServiceClient', +'ContentType', +'ListAssetsRequest', +'ListAssetsResponse', +'Resource', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json new file mode 100644 index 00000000..2c3088cd --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1p5beta1", + "protoPackage": "google.cloud.asset.v1p5beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "ListAssets": { + "methods": [ + "list_assets" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "ListAssets": { + "methods": [ + "list_assets" + ] + } + } + }, + "rest": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "ListAssets": { + "methods": [ + "list_assets" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py new file mode 100644 index 00000000..360a0d13 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py new file mode 100644 index 00000000..89a37dc9 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py new file mode 100644 index 00000000..542f923f --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AssetServiceClient +from .async_client import AssetServiceAsyncClient + +__all__ = ( + 'AssetServiceClient', + 'AssetServiceAsyncClient', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..b8e79ce3 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py @@ -0,0 +1,330 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.asset_v1p5beta1 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.cloud.asset_v1p5beta1.services.asset_service import pagers +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .client import AssetServiceClient + + +class AssetServiceAsyncClient: + """Asset service definition.""" + + _client: AssetServiceClient + + DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT + + access_level_path = staticmethod(AssetServiceClient.access_level_path) + parse_access_level_path = staticmethod(AssetServiceClient.parse_access_level_path) + access_policy_path = staticmethod(AssetServiceClient.access_policy_path) + parse_access_policy_path = staticmethod(AssetServiceClient.parse_access_policy_path) + asset_path = staticmethod(AssetServiceClient.asset_path) + parse_asset_path = staticmethod(AssetServiceClient.parse_asset_path) + service_perimeter_path = staticmethod(AssetServiceClient.service_perimeter_path) + parse_service_perimeter_path = staticmethod(AssetServiceClient.parse_service_perimeter_path) + common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AssetServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AssetServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) + common_project_path = staticmethod(AssetServiceClient.common_project_path) + parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) + common_location_path = staticmethod(AssetServiceClient.common_location_path) + parse_common_location_path = staticmethod(AssetServiceClient.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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: + AssetServiceAsyncClient: The constructed client. + """ + return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_assets(self, + request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsAsyncPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + .. 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 asset_v1p5beta1 + + async def sample_list_assets(): + # Create a client + client = asset_v1p5beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p5beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.asset_v1p5beta1.types.ListAssetsRequest, dict]]): + The request object. ListAssets request. + parent (:class:`str`): + Required. Name of the organization or project the assets + belong to. Format: "organizations/[organization-number]" + (such as "organizations/123"), "projects/[project-id]" + (such as "projects/my-project-id"), or + "projects/[project-number]" (such as "projects/12345"). + + 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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsAsyncPager: + ListAssets response. + + 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 = asset_service.ListAssetsRequest(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_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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.ListAssetsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AssetServiceAsyncClient": + 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__ = ( + "AssetServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py new file mode 100644 index 00000000..7de4794f --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py @@ -0,0 +1,558 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast + +from google.cloud.asset_v1p5beta1 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.cloud.asset_v1p5beta1.services.asset_service import pagers +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .transports.rest import AssetServiceRestTransport + + +class AssetServiceClientMeta(type): + """Metaclass for the AssetService 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[AssetServiceTransport]] + _transport_registry["grpc"] = AssetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AssetServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AssetServiceTransport]: + """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 AssetServiceClient(metaclass=AssetServiceClientMeta): + """Asset service definition.""" + + @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 = "cloudasset.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: + AssetServiceClient: 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: + AssetServiceClient: 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) -> AssetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AssetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def access_level_path(access_policy: str,access_level: str,) -> str: + """Returns a fully-qualified access_level string.""" + return "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) + + @staticmethod + def parse_access_level_path(path: str) -> Dict[str,str]: + """Parses a access_level path into its component segments.""" + m = re.match(r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def access_policy_path(access_policy: str,) -> str: + """Returns a fully-qualified access_policy string.""" + return "accessPolicies/{access_policy}".format(access_policy=access_policy, ) + + @staticmethod + def parse_access_policy_path(path: str) -> Dict[str,str]: + """Parses a access_policy path into its component segments.""" + m = re.match(r"^accessPolicies/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def asset_path() -> str: + """Returns a fully-qualified asset string.""" + return "*".format() + + @staticmethod + def parse_asset_path(path: str) -> Dict[str,str]: + """Parses a asset path into its component segments.""" + m = re.match(r"^.*$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_perimeter_path(access_policy: str,service_perimeter: str,) -> str: + """Returns a fully-qualified service_perimeter string.""" + return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) + + @staticmethod + def parse_service_perimeter_path(path: str) -> Dict[str,str]: + """Parses a service_perimeter path into its component segments.""" + m = re.match(r"^accessPolicies/(?P.+?)/servicePerimeters/(?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, AssetServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): + # transport is a AssetServiceTransport 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_assets(self, + request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + .. 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 asset_v1p5beta1 + + def sample_list_assets(): + # Create a client + client = asset_v1p5beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p5beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.asset_v1p5beta1.types.ListAssetsRequest, dict]): + The request object. ListAssets request. + parent (str): + Required. Name of the organization or project the assets + belong to. Format: "organizations/[organization-number]" + (such as "organizations/123"), "projects/[project-id]" + (such as "projects/my-project-id"), or + "projects/[project-number]" (such as "projects/12345"). + + 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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsPager: + ListAssets response. + + 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 asset_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ListAssetsRequest): + request = asset_service.ListAssetsRequest(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_assets] + + # 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.ListAssetsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AssetServiceClient": + 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() + + + + + + + + + + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AssetServiceClient", +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py new file mode 100644 index 00000000..95a1ce7e --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator + +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` + 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[..., asset_service.ListAssetsResponse], + request: asset_service.ListAssetsRequest, + response: asset_service.ListAssetsResponse, + *, + 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.asset_v1p5beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.asset_v1p5beta1.types.ListAssetsResponse): + 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 = asset_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[asset_service.ListAssetsResponse]: + 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[assets.Asset]: + for page in self.pages: + yield from page.assets + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``assets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``assets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` + 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[asset_service.ListAssetsResponse]], + request: asset_service.ListAssetsRequest, + response: asset_service.ListAssetsResponse, + *, + 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.asset_v1p5beta1.types.ListAssetsRequest): + The initial request object. + response (google.cloud.asset_v1p5beta1.types.ListAssetsResponse): + 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 = asset_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[asset_service.ListAssetsResponse]: + 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[assets.Asset]: + async def async_generator(): + async for page in self.pages: + for response in page.assets: + 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/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..c34a5f8f --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AssetServiceTransport +from .grpc import AssetServiceGrpcTransport +from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport +from .rest import AssetServiceRestTransport +from .rest import AssetServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport +_transport_registry['rest'] = AssetServiceRestTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', + 'AssetServiceRestTransport', + 'AssetServiceRestInterceptor', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..3117d03b --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.asset_v1p5beta1 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.cloud.asset_v1p5beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AssetServiceTransport(abc.ABC): + """Abstract transport class for AssetService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + ) + + DEFAULT_HOST: str = 'cloudasset.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_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_retry=retries.Retry( +initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( + 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_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + Union[ + asset_service.ListAssetsResponse, + Awaitable[asset_service.ListAssetsResponse] + ]]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AssetServiceTransport', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..6f7e71a0 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.asset_v1p5beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO + + +class AssetServiceGrpcTransport(AssetServiceTransport): + """gRPC backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + asset_service.ListAssetsResponse]: + r"""Return a callable for the list assets method over gRPC. + + Lists assets with time and resource types and returns + paged results in response. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + 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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p5beta1.AssetService/ListAssets', + request_serializer=asset_service.ListAssetsRequest.serialize, + response_deserializer=asset_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AssetServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..ad3e4a30 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.asset_v1p5beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore +from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import AssetServiceGrpcTransport + + +class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): + """gRPC AsyncIO backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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 = 'cloudasset.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_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + Awaitable[asset_service.ListAssetsResponse]]: + r"""Return a callable for the list assets method over gRPC. + + Lists assets with time and resource types and returns + paged results in response. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + 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_assets' not in self._stubs: + self._stubs['list_assets'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p5beta1.AssetService/ListAssets', + request_serializer=asset_service.ListAssetsRequest.serialize, + response_deserializer=asset_service.ListAssetsResponse.deserialize, + ) + return self._stubs['list_assets'] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py new file mode 100644 index 00000000..bd8cbb5d --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py @@ -0,0 +1,289 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +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 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.asset_v1p5beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore + +from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: + """Interceptor for AssetService. + + 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 AssetServiceRestTransport. + + .. code-block:: python + class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): + def pre_list_assets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assets(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) + client = AssetServiceClient(transport=transport) + + + """ + def pre_list_assets(self, request: asset_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AssetService server. + """ + return request, metadata + + def post_list_assets(self, response: asset_service.ListAssetsResponse) -> asset_service.ListAssetsResponse: + """Post-rpc interceptor for list_assets + + Override in a subclass to manipulate the response + after it is returned by the AssetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AssetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AssetServiceRestInterceptor + + +class AssetServiceRestTransport(AssetServiceTransport): + """REST backend transport for AssetService. + + Asset service definition. + + 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListAssets(AssetServiceRestStub): + def __hash__(self): + return hash("ListAssets") + + __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: asset_service.ListAssetsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> asset_service.ListAssetsResponse: + r"""Call the list assets method over HTTP. + + Args: + request (~.asset_service.ListAssetsRequest): + The request object. ListAssets request. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.asset_service.ListAssetsResponse: + ListAssets response. + """ + + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1p5beta1/{parent=*/*}/assets', + }, + ] + request, metadata = self._interceptor.pre_list_assets(request, metadata) + pb_request = asset_service.ListAssetsRequest.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 = asset_service.ListAssetsResponse() + pb_resp = asset_service.ListAssetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assets(resp) + return resp + + @property + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + asset_service.ListAssetsResponse]: + # 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._ListAssets(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AssetServiceRestTransport', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py new file mode 100644 index 00000000..e6aeedca --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .asset_service import ( + ListAssetsRequest, + ListAssetsResponse, + ContentType, +) +from .assets import ( + Asset, + Resource, +) + +__all__ = ( + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ContentType', + 'Asset', + 'Resource', +) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py new file mode 100644 index 00000000..493e4506 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.asset_v1p5beta1.types import assets as gca_assets +from google.protobuf import timestamp_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p5beta1', + manifest={ + 'ContentType', + 'ListAssetsRequest', + 'ListAssetsResponse', + }, +) + + +class ContentType(proto.Enum): + r"""Asset content type. + + Values: + CONTENT_TYPE_UNSPECIFIED (0): + Unspecified content type. + RESOURCE (1): + Resource metadata. + IAM_POLICY (2): + The actual IAM policy set on a resource. + ORG_POLICY (4): + The organization policy set on an asset. + ACCESS_POLICY (5): + The Access Context Manager policy set on an + asset. + """ + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + ORG_POLICY = 4 + ACCESS_POLICY = 5 + + +class ListAssetsRequest(proto.Message): + r"""ListAssets request. + + Attributes: + parent (str): + Required. Name of the organization or project the assets + belong to. Format: "organizations/[organization-number]" + (such as "organizations/123"), "projects/[project-id]" (such + as "projects/my-project-id"), or "projects/[project-number]" + (such as "projects/12345"). + read_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp to take an asset snapshot. This can + only be set to a timestamp between the current + time and the current time minus 35 days + (inclusive). If not specified, the current time + will be used. Due to delays in resource data + collection and indexing, there is a volatile + window during which running the same query may + get different results. + asset_types (MutableSequence[str]): + A list of asset types to take a snapshot for. For example: + "compute.googleapis.com/Disk". + + Regular expression is also supported. For example: + + - "compute.googleapis.com.*" snapshots resources whose + asset type starts with "compute.googleapis.com". + - ".*Instance" snapshots resources whose asset type ends + with "Instance". + - ".*Instance.*" snapshots resources whose asset type + contains "Instance". + + See `RE2 `__ for + all supported regular expression syntax. If the regular + expression does not match any supported asset type, an + INVALID_ARGUMENT error will be returned. + + If specified, only matching assets will be returned, + otherwise, it will snapshot all asset types. See + `Introduction to Cloud Asset + Inventory `__ + for all supported asset types. + content_type (google.cloud.asset_v1p5beta1.types.ContentType): + Asset content type. If not specified, no + content but the asset name will be returned. + page_size (int): + The maximum number of assets to be returned + in a single response. Default is 100, minimum is + 1, and maximum is 1000. + page_token (str): + The ``next_page_token`` returned from the previous + ``ListAssetsResponse``, or unspecified for the first + ``ListAssetsRequest``. It is a continuation of a prior + ``ListAssets`` call, and the API should return the next page + of assets. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + asset_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type: 'ContentType' = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + page_size: int = proto.Field( + proto.INT32, + number=5, + ) + page_token: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListAssetsResponse(proto.Message): + r"""ListAssets response. + + Attributes: + read_time (google.protobuf.timestamp_pb2.Timestamp): + Time the snapshot was taken. + assets (MutableSequence[google.cloud.asset_v1p5beta1.types.Asset]): + Assets. + next_page_token (str): + Token to retrieve the next page of results. + It expires 72 hours after the page token for the + first page is generated. Set to empty if there + are no remaining results. + """ + + @property + def raw_page(self): + return self + + read_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + assets: MutableSequence[gca_assets.Asset] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gca_assets.Asset, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py new file mode 100644 index 00000000..7ab19dd2 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_level_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p5beta1', + manifest={ + 'Asset', + 'Resource', + }, +) + + +class Asset(proto.Message): + r"""An asset in Google Cloud. An asset can be any resource in the Google + Cloud `resource + hierarchy `__, + a resource outside the Google Cloud resource hierarchy (such as + Google Kubernetes Engine clusters and objects), or a policy (e.g. + IAM policy). See `Supported asset + types `__ + for more information. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + The full name of the asset. Example: + ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`` + + See `Resource + names `__ + for more information. + asset_type (str): + The type of the asset. Example: + ``compute.googleapis.com/Disk`` + + See `Supported asset + types `__ + for more information. + resource (google.cloud.asset_v1p5beta1.types.Resource): + A representation of the resource. + iam_policy (google.iam.v1.policy_pb2.Policy): + A representation of the IAM policy set on a Google Cloud + resource. There can be a maximum of one IAM policy set on + any given resource. In addition, IAM policies inherit their + granted access scope from any policies set on parent + resources in the resource hierarchy. Therefore, the + effectively policy is the union of both the policy set on + this resource and each policy set on all of the resource's + ancestry resource levels in the hierarchy. See `this + topic `__ + for more information. + org_policy (MutableSequence[google.cloud.orgpolicy.v1.orgpolicy_pb2.Policy]): + A representation of an `organization + policy `__. + There can be more than one organization policy with + different constraints set on a given resource. + access_policy (google.identity.accesscontextmanager.v1.access_policy_pb2.AccessPolicy): + Please also refer to the `access policy user + guide `__. + + This field is a member of `oneof`_ ``access_context_policy``. + access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): + Please also refer to the `access level user + guide `__. + + This field is a member of `oneof`_ ``access_context_policy``. + service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): + Please also refer to the `service perimeter user + guide `__. + + This field is a member of `oneof`_ ``access_context_policy``. + ancestors (MutableSequence[str]): + The ancestry path of an asset in Google Cloud `resource + hierarchy `__, + represented as a list of relative resource names. An + ancestry path starts with the closest ancestor in the + hierarchy and ends at root. If the asset is a project, + folder, or organization, the ancestry path starts from the + asset itself. + + Example: + ``["projects/123456789", "folders/5432", "organizations/1234"]`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + asset_type: str = proto.Field( + proto.STRING, + number=2, + ) + resource: 'Resource' = proto.Field( + proto.MESSAGE, + number=3, + message='Resource', + ) + iam_policy: policy_pb2.Policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + org_policy: MutableSequence[orgpolicy_pb2.Policy] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=orgpolicy_pb2.Policy, + ) + access_policy: access_policy_pb2.AccessPolicy = proto.Field( + proto.MESSAGE, + number=7, + oneof='access_context_policy', + message=access_policy_pb2.AccessPolicy, + ) + access_level: access_level_pb2.AccessLevel = proto.Field( + proto.MESSAGE, + number=8, + oneof='access_context_policy', + message=access_level_pb2.AccessLevel, + ) + service_perimeter: service_perimeter_pb2.ServicePerimeter = proto.Field( + proto.MESSAGE, + number=9, + oneof='access_context_policy', + message=service_perimeter_pb2.ServicePerimeter, + ) + ancestors: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + + +class Resource(proto.Message): + r"""A representation of a Google Cloud resource. + + Attributes: + version (str): + The API version. Example: "v1". + discovery_document_uri (str): + The URL of the discovery document containing the resource's + JSON schema. Example: + ``https://www.googleapis.com/discovery/v1/apis/compute/v1/rest`` + + This value is unspecified for resources that do not have an + API based on a discovery document, such as Cloud Bigtable. + discovery_name (str): + The JSON schema name listed in the discovery document. + Example: ``Project`` + + This value is unspecified for resources that do not have an + API based on a discovery document, such as Cloud Bigtable. + resource_url (str): + The REST URL for accessing the resource. An HTTP ``GET`` + request using this URL returns the resource itself. Example: + ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`` + + This value is unspecified for resources without a REST API. + parent (str): + The full name of the immediate parent of this resource. See + `Resource + Names `__ + for more information. + + For Google Cloud assets, this value is the parent resource + defined in the `IAM policy + hierarchy `__. + Example: + ``//cloudresourcemanager.googleapis.com/projects/my_project_123`` + + For third-party assets, this field may be set differently. + data (google.protobuf.struct_pb2.Struct): + The content of the resource, in which some + sensitive fields are removed and may not be + present. + """ + + version: str = proto.Field( + proto.STRING, + number=1, + ) + discovery_document_uri: str = proto.Field( + proto.STRING, + number=2, + ) + discovery_name: str = proto.Field( + proto.STRING, + number=3, + ) + resource_url: str = proto.Field( + proto.STRING, + number=4, + ) + parent: str = proto.Field( + proto.STRING, + number=5, + ) + data: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p5beta1/mypy.ini b/owl-bot-staging/v1p5beta1/mypy.ini new file mode 100644 index 00000000..574c5aed --- /dev/null +++ b/owl-bot-staging/v1p5beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/v1p5beta1/noxfile.py b/owl-bot-staging/v1p5beta1/noxfile.py new file mode 100644 index 00000000..f589535f --- /dev/null +++ b/owl-bot-staging/v1p5beta1/noxfile.py @@ -0,0 +1,184 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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/asset_v1p5beta1/', + '--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==7.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/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py b/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py new file mode 100644 index 00000000..2f32e298 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# 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-asset + + +# [START cloudasset_v1p5beta1_generated_AssetService_ListAssets_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 asset_v1p5beta1 + + +async def sample_list_assets(): + # Create a client + client = asset_v1p5beta1.AssetServiceAsyncClient() + + # Initialize request argument(s) + request = asset_v1p5beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudasset_v1p5beta1_generated_AssetService_ListAssets_async] diff --git a/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py b/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py new file mode 100644 index 00000000..3c5deb0a --- /dev/null +++ b/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAssets +# 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-asset + + +# [START cloudasset_v1p5beta1_generated_AssetService_ListAssets_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 asset_v1p5beta1 + + +def sample_list_assets(): + # Create a client + client = asset_v1p5beta1.AssetServiceClient() + + # Initialize request argument(s) + request = asset_v1p5beta1.ListAssetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assets(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudasset_v1p5beta1_generated_AssetService_ListAssets_sync] diff --git a/owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json b/owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json new file mode 100644 index 00000000..13ffc229 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json @@ -0,0 +1,176 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.asset.v1p5beta1", + "version": "v1p5beta1" + } + ], + "language": "PYTHON", + "name": "google-cloud-asset", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.asset_v1p5beta1.AssetServiceAsyncClient", + "shortName": "AssetServiceAsyncClient" + }, + "fullName": "google.cloud.asset_v1p5beta1.AssetServiceAsyncClient.list_assets", + "method": { + "fullName": "google.cloud.asset.v1p5beta1.AssetService.ListAssets", + "service": { + "fullName": "google.cloud.asset.v1p5beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p5beta1.types.ListAssetsRequest" + }, + { + "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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsAsyncPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p5beta1_generated_AssetService_ListAssets_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": "cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.asset_v1p5beta1.AssetServiceClient", + "shortName": "AssetServiceClient" + }, + "fullName": "google.cloud.asset_v1p5beta1.AssetServiceClient.list_assets", + "method": { + "fullName": "google.cloud.asset.v1p5beta1.AssetService.ListAssets", + "service": { + "fullName": "google.cloud.asset.v1p5beta1.AssetService", + "shortName": "AssetService" + }, + "shortName": "ListAssets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.asset_v1p5beta1.types.ListAssetsRequest" + }, + { + "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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsPager", + "shortName": "list_assets" + }, + "description": "Sample for ListAssets", + "file": "cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudasset_v1p5beta1_generated_AssetService_ListAssets_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": "cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py" + } + ] +} diff --git a/owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py b/owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py new file mode 100644 index 00000000..ec38c673 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py @@ -0,0 +1,176 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 assetCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), + } + + 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=assetCallTransformer(), +): + """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 asset 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/v1p5beta1/setup.py b/owl-bot-staging/v1p5beta1/setup.py new file mode 100644 index 00000000..166120b0 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/setup.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-asset' + + +description = "Google Cloud Asset API client library" + +version = {} +with open(os.path.join(package_root, 'google/cloud/asset/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-asset" + +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/v1p5beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.10.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.11.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.12.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.7.txt new file mode 100644 index 00000000..2beecf99 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.8.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.9.txt new file mode 100644 index 00000000..ad3f0fa5 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/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/v1p5beta1/tests/__init__.py b/owl-bot-staging/v1p5beta1/tests/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/__init__.py b/owl-bot-staging/v1p5beta1/tests/unit/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py new file mode 100644 index 00000000..1b4db446 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py new file mode 100644 index 00000000..4ad268f9 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -0,0 +1,1988 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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 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.asset_v1p5beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p5beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p5beta1.services.asset_service import pagers +from google.cloud.asset_v1p5beta1.services.asset_service import transports +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +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 AssetServiceClient._get_default_mtls_endpoint(None) is None + assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, "grpc"), + (AssetServiceAsyncClient, "grpc_asyncio"), + (AssetServiceClient, "rest"), +]) +def test_asset_service_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 == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudasset.googleapis.com' + ) + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceRestTransport, + ] + assert transport in available_transports + + transport = AssetServiceClient.get_transport_class("grpc") + assert transport == transports.AssetServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_asset_service_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", [ + AssetServiceClient, AssetServiceAsyncClient +]) +@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) +@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), +]) +def test_asset_service_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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), +]) +def test_asset_service_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_asset_service_client_client_options_from_dict(): + with mock.patch('google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListAssetsRequest, + dict, +]) +def test_list_assets(request_type, transport: str = 'grpc'): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + response = client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_assets_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 = AssetServiceClient( + 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_assets), + '__call__') as call: + client.list_assets() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListAssetsRequest() + +@pytest.mark.asyncio +async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListAssetsRequest): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional 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_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_assets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ListAssetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_assets_async_from_dict(): + await test_list_assets_async(request_type=dict) + + +def test_list_assets_field_headers(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = asset_service.ListAssetsResponse() + client.list_assets(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_assets_field_headers_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = asset_service.ListAssetsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) + await client.list_assets(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_assets_flattened(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListAssetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_assets( + 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_assets_flattened_error(): + client = AssetServiceClient( + 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_assets( + asset_service.ListAssetsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_assets_flattened_async(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = asset_service.ListAssetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_assets( + 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_assets_flattened_error_async(): + client = AssetServiceAsyncClient( + 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_assets( + asset_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_pager(transport_name: str = "grpc"): + client = AssetServiceClient( + 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_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_assets(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.Asset) + for i in results) +def test_list_assets_pages(transport_name: str = "grpc"): + client = AssetServiceClient( + 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_assets), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_assets(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_assets_async_pager(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_assets(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, assets.Asset) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_assets_async_pages(): + client = AssetServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_assets), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_assets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize("request_type", [ + asset_service.ListAssetsRequest, + dict, +]) +def test_list_assets_rest(request_type): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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 = asset_service.ListAssetsResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.list_assets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssetsPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_assets_rest_required_fields(request_type=asset_service.ListAssetsRequest): + transport_class = transports.AssetServiceRestTransport + + 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_assets._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_assets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("asset_types", "content_type", "page_size", "page_token", "read_time", )) + 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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = asset_service.ListAssetsResponse() + # 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 + + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.list_assets(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_assets_rest_unset_required_fields(): + transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_assets._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assetTypes", "contentType", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assets_rest_interceptors(null_interceptor): + transport = transports.AssetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), + ) + client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_assets") as post, \ + mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_assets") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = asset_service.ListAssetsRequest.pb(asset_service.ListAssetsRequest()) + 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 = asset_service.ListAssetsResponse.to_json(asset_service.ListAssetsResponse()) + + request = asset_service.ListAssetsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = asset_service.ListAssetsResponse() + + client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListAssetsRequest): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'sample1/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_assets(request) + + +def test_list_assets_rest_flattened(): + client = AssetServiceClient( + 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 = asset_service.ListAssetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'sample1/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 + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.list_assets(**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/v1p5beta1/{parent=*/*}/assets" % client.transport._host, args[1]) + + +def test_list_assets_rest_flattened_error(transport: str = 'rest'): + client = AssetServiceClient( + 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_assets( + asset_service.ListAssetsRequest(), + parent='parent_value', + ) + + +def test_list_assets_rest_pager(transport: str = 'rest'): + client = AssetServiceClient( + 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 = ( + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + assets.Asset(), + ], + next_page_token='abc', + ), + asset_service.ListAssetsResponse( + assets=[], + next_page_token='def', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + ], + next_page_token='ghi', + ), + asset_service.ListAssetsResponse( + assets=[ + assets.Asset(), + assets.Asset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(asset_service.ListAssetsResponse.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': 'sample1/sample2'} + + pager = client.list_assets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, assets.Asset) + for i in results) + + pages = list(client.list_assets(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AssetServiceClient( + 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 = AssetServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AssetServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AssetServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AssetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AssetServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, +]) +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 = AssetServiceClient.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 = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AssetServiceGrpcTransport, + ) + +def test_asset_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_asset_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AssetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_assets', + ) + 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_asset_service_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.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + 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_asset_service_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.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport() + adc.assert_called_once() + + +def test_asset_service_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) + AssetServiceClient() + 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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + transports.AssetServiceRestTransport, + ], +) +def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_asset_service_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( + "cloudasset.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="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( + 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_asset_service_host_no_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_asset_service_host_with_port(transport_name): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudasset.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudasset.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_asset_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AssetServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AssetServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_assets._session + session2 = client2.transport.list_assets._session + assert session1 != session2 +def test_asset_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcTransport( + 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_asset_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AssetServiceGrpcAsyncIOTransport( + 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) +def test_asset_service_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_access_level_path(): + access_policy = "squid" + access_level = "clam" + expected = "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) + actual = AssetServiceClient.access_level_path(access_policy, access_level) + assert expected == actual + + +def test_parse_access_level_path(): + expected = { + "access_policy": "whelk", + "access_level": "octopus", + } + path = AssetServiceClient.access_level_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_access_level_path(path) + assert expected == actual + +def test_access_policy_path(): + access_policy = "oyster" + expected = "accessPolicies/{access_policy}".format(access_policy=access_policy, ) + actual = AssetServiceClient.access_policy_path(access_policy) + assert expected == actual + + +def test_parse_access_policy_path(): + expected = { + "access_policy": "nudibranch", + } + path = AssetServiceClient.access_policy_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_access_policy_path(path) + assert expected == actual + +def test_asset_path(): + expected = "*".format() + actual = AssetServiceClient.asset_path() + assert expected == actual + + +def test_parse_asset_path(): + expected = { + } + path = AssetServiceClient.asset_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_asset_path(path) + assert expected == actual + +def test_service_perimeter_path(): + access_policy = "cuttlefish" + service_perimeter = "mussel" + expected = "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) + actual = AssetServiceClient.service_perimeter_path(access_policy, service_perimeter) + assert expected == actual + + +def test_parse_service_perimeter_path(): + expected = { + "access_policy": "winkle", + "service_perimeter": "nautilus", + } + path = AssetServiceClient.service_perimeter_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_service_perimeter_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AssetServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = AssetServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format(folder=folder, ) + actual = AssetServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = AssetServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AssetServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = AssetServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format(project=project, ) + actual = AssetServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = AssetServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AssetServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = AssetServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( + 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_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = AssetServiceClient( + 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 = AssetServiceClient( + 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", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), +]) +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 2aaf4d6d4604f8e03e0c3ef1552fc2384ac19103 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Fri, 13 Oct 2023 18:08:47 +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 --- 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 - owl-bot-staging/v1/docs/_static/custom.css | 3 - .../v1/docs/asset_v1/asset_service.rst | 10 - owl-bot-staging/v1/docs/asset_v1/services.rst | 6 - owl-bot-staging/v1/docs/asset_v1/types.rst | 6 - owl-bot-staging/v1/docs/conf.py | 376 - owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/cloud/asset/__init__.py | 185 - .../v1/google/cloud/asset/gapic_version.py | 16 - .../v1/google/cloud/asset/py.typed | 2 - .../v1/google/cloud/asset_v1/__init__.py | 186 - .../google/cloud/asset_v1/gapic_metadata.json | 373 - .../v1/google/cloud/asset_v1/gapic_version.py | 16 - .../v1/google/cloud/asset_v1/py.typed | 2 - .../cloud/asset_v1/services/__init__.py | 15 - .../services/asset_service/__init__.py | 22 - .../services/asset_service/async_client.py | 3169 ---- .../asset_v1/services/asset_service/client.py | 3329 ---- .../asset_v1/services/asset_service/pagers.py | 866 - .../asset_service/transports/__init__.py | 38 - .../services/asset_service/transports/base.py | 580 - .../services/asset_service/transports/grpc.py | 959 -- .../asset_service/transports/grpc_asyncio.py | 958 -- .../services/asset_service/transports/rest.py | 2899 ---- .../google/cloud/asset_v1/types/__init__.py | 180 - .../cloud/asset_v1/types/asset_service.py | 4036 ----- .../v1/google/cloud/asset_v1/types/assets.py | 1683 -- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 184 - ..._asset_service_analyze_iam_policy_async.py | 55 - ...ce_analyze_iam_policy_longrunning_async.py | 63 - ...ice_analyze_iam_policy_longrunning_sync.py | 63 - ...d_asset_service_analyze_iam_policy_sync.py | 55 - ...erated_asset_service_analyze_move_async.py | 53 - ...nerated_asset_service_analyze_move_sync.py | 53 - ...sset_service_analyze_org_policies_async.py | 54 - ...asset_service_analyze_org_policies_sync.py | 54 - ...nalyze_org_policy_governed_assets_async.py | 54 - ...analyze_org_policy_governed_assets_sync.py | 54 - ...ze_org_policy_governed_containers_async.py | 54 - ...yze_org_policy_governed_containers_sync.py | 54 - ..._service_batch_get_assets_history_async.py | 52 - ...t_service_batch_get_assets_history_sync.py | 52 - ..._batch_get_effective_iam_policies_async.py | 53 - ...e_batch_get_effective_iam_policies_sync.py | 53 - ...nerated_asset_service_create_feed_async.py | 57 - ...enerated_asset_service_create_feed_sync.py | 57 - ..._asset_service_create_saved_query_async.py | 53 - ...d_asset_service_create_saved_query_sync.py | 53 - ...nerated_asset_service_delete_feed_async.py | 50 - ...enerated_asset_service_delete_feed_sync.py | 50 - ..._asset_service_delete_saved_query_async.py | 50 - ...d_asset_service_delete_saved_query_sync.py | 50 - ...rated_asset_service_export_assets_async.py | 60 - ...erated_asset_service_export_assets_sync.py | 60 - ..._generated_asset_service_get_feed_async.py | 52 - ...1_generated_asset_service_get_feed_sync.py | 52 - ...ted_asset_service_get_saved_query_async.py | 52 - ...ated_asset_service_get_saved_query_sync.py | 52 - ...nerated_asset_service_list_assets_async.py | 53 - ...enerated_asset_service_list_assets_sync.py | 53 - ...enerated_asset_service_list_feeds_async.py | 52 - ...generated_asset_service_list_feeds_sync.py | 52 - ..._asset_service_list_saved_queries_async.py | 53 - ...d_asset_service_list_saved_queries_sync.py | 53 - ...erated_asset_service_query_assets_async.py | 53 - ...nerated_asset_service_query_assets_sync.py | 53 - ...t_service_search_all_iam_policies_async.py | 53 - ...et_service_search_all_iam_policies_sync.py | 53 - ...sset_service_search_all_resources_async.py | 53 - ...asset_service_search_all_resources_sync.py | 53 - ...nerated_asset_service_update_feed_async.py | 55 - ...enerated_asset_service_update_feed_sync.py | 55 - ..._asset_service_update_saved_query_async.py | 51 - ...d_asset_service_update_saved_query_sync.py | 51 - ...nippet_metadata_google.cloud.asset.v1.json | 3746 ----- .../v1/scripts/fixup_asset_v1_keywords.py | 198 - 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 - .../v1/tests/unit/gapic/asset_v1/__init__.py | 16 - .../unit/gapic/asset_v1/test_asset_service.py | 13601 ---------------- owl-bot-staging/v1p1beta1/.coveragerc | 13 - owl-bot-staging/v1p1beta1/.flake8 | 33 - owl-bot-staging/v1p1beta1/MANIFEST.in | 2 - owl-bot-staging/v1p1beta1/README.rst | 49 - .../v1p1beta1/docs/_static/custom.css | 3 - .../docs/asset_v1p1beta1/asset_service.rst | 10 - .../docs/asset_v1p1beta1/services.rst | 6 - .../v1p1beta1/docs/asset_v1p1beta1/types.rst | 6 - owl-bot-staging/v1p1beta1/docs/conf.py | 376 - owl-bot-staging/v1p1beta1/docs/index.rst | 7 - .../v1p1beta1/google/cloud/asset/__init__.py | 41 - .../google/cloud/asset/gapic_version.py | 16 - .../v1p1beta1/google/cloud/asset/py.typed | 2 - .../google/cloud/asset_v1p1beta1/__init__.py | 42 - .../cloud/asset_v1p1beta1/gapic_metadata.json | 58 - .../cloud/asset_v1p1beta1/gapic_version.py | 16 - .../google/cloud/asset_v1p1beta1/py.typed | 2 - .../asset_v1p1beta1/services/__init__.py | 15 - .../services/asset_service/__init__.py | 22 - .../services/asset_service/async_client.py | 494 - .../services/asset_service/client.py | 679 - .../services/asset_service/pagers.py | 261 - .../asset_service/transports/__init__.py | 38 - .../services/asset_service/transports/base.py | 177 - .../services/asset_service/transports/grpc.py | 303 - .../asset_service/transports/grpc_asyncio.py | 302 - .../services/asset_service/transports/rest.py | 399 - .../cloud/asset_v1p1beta1/types/__init__.py | 36 - .../asset_v1p1beta1/types/asset_service.py | 212 - .../cloud/asset_v1p1beta1/types/assets.py | 203 - owl-bot-staging/v1p1beta1/mypy.ini | 3 - owl-bot-staging/v1p1beta1/noxfile.py | 184 - ...t_service_search_all_iam_policies_async.py | 53 - ...et_service_search_all_iam_policies_sync.py | 53 - ...sset_service_search_all_resources_async.py | 53 - ...asset_service_search_all_resources_sync.py | 53 - ...metadata_google.cloud.asset.v1p1beta1.json | 361 - .../scripts/fixup_asset_v1p1beta1_keywords.py | 177 - owl-bot-staging/v1p1beta1/setup.py | 91 - .../v1p1beta1/testing/constraints-3.10.txt | 7 - .../v1p1beta1/testing/constraints-3.11.txt | 7 - .../v1p1beta1/testing/constraints-3.12.txt | 7 - .../v1p1beta1/testing/constraints-3.7.txt | 10 - .../v1p1beta1/testing/constraints-3.8.txt | 7 - .../v1p1beta1/testing/constraints-3.9.txt | 7 - owl-bot-staging/v1p1beta1/tests/__init__.py | 16 - .../v1p1beta1/tests/unit/__init__.py | 16 - .../v1p1beta1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/asset_v1p1beta1/__init__.py | 16 - .../asset_v1p1beta1/test_asset_service.py | 2674 --- owl-bot-staging/v1p2beta1/.coveragerc | 13 - owl-bot-staging/v1p2beta1/.flake8 | 33 - owl-bot-staging/v1p2beta1/MANIFEST.in | 2 - owl-bot-staging/v1p2beta1/README.rst | 49 - .../v1p2beta1/docs/_static/custom.css | 3 - .../docs/asset_v1p2beta1/asset_service.rst | 6 - .../docs/asset_v1p2beta1/services.rst | 6 - .../v1p2beta1/docs/asset_v1p2beta1/types.rst | 6 - owl-bot-staging/v1p2beta1/docs/conf.py | 376 - owl-bot-staging/v1p2beta1/docs/index.rst | 7 - .../v1p2beta1/google/cloud/asset/__init__.py | 59 - .../google/cloud/asset/gapic_version.py | 16 - .../v1p2beta1/google/cloud/asset/py.typed | 2 - .../google/cloud/asset_v1p2beta1/__init__.py | 60 - .../cloud/asset_v1p2beta1/gapic_metadata.json | 103 - .../cloud/asset_v1p2beta1/gapic_version.py | 16 - .../google/cloud/asset_v1p2beta1/py.typed | 2 - .../asset_v1p2beta1/services/__init__.py | 15 - .../services/asset_service/__init__.py | 22 - .../services/asset_service/async_client.py | 751 - .../services/asset_service/client.py | 934 -- .../asset_service/transports/__init__.py | 38 - .../services/asset_service/transports/base.py | 226 - .../services/asset_service/transports/grpc.py | 372 - .../asset_service/transports/grpc_asyncio.py | 371 - .../services/asset_service/transports/rest.py | 747 - .../cloud/asset_v1p2beta1/types/__init__.py | 54 - .../asset_v1p2beta1/types/asset_service.py | 346 - .../cloud/asset_v1p2beta1/types/assets.py | 218 - owl-bot-staging/v1p2beta1/mypy.ini | 3 - owl-bot-staging/v1p2beta1/noxfile.py | 184 - ...nerated_asset_service_create_feed_async.py | 57 - ...enerated_asset_service_create_feed_sync.py | 57 - ...nerated_asset_service_delete_feed_async.py | 50 - ...enerated_asset_service_delete_feed_sync.py | 50 - ..._generated_asset_service_get_feed_async.py | 52 - ...1_generated_asset_service_get_feed_sync.py | 52 - ...enerated_asset_service_list_feeds_async.py | 52 - ...generated_asset_service_list_feeds_sync.py | 52 - ...nerated_asset_service_update_feed_async.py | 55 - ...enerated_asset_service_update_feed_sync.py | 55 - ...metadata_google.cloud.asset.v1p2beta1.json | 814 - .../scripts/fixup_asset_v1p2beta1_keywords.py | 180 - owl-bot-staging/v1p2beta1/setup.py | 91 - .../v1p2beta1/testing/constraints-3.10.txt | 7 - .../v1p2beta1/testing/constraints-3.11.txt | 7 - .../v1p2beta1/testing/constraints-3.12.txt | 7 - .../v1p2beta1/testing/constraints-3.7.txt | 10 - .../v1p2beta1/testing/constraints-3.8.txt | 7 - .../v1p2beta1/testing/constraints-3.9.txt | 7 - owl-bot-staging/v1p2beta1/tests/__init__.py | 16 - .../v1p2beta1/tests/unit/__init__.py | 16 - .../v1p2beta1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/asset_v1p2beta1/__init__.py | 16 - .../asset_v1p2beta1/test_asset_service.py | 3600 ---- owl-bot-staging/v1p5beta1/.coveragerc | 13 - owl-bot-staging/v1p5beta1/.flake8 | 33 - owl-bot-staging/v1p5beta1/MANIFEST.in | 2 - owl-bot-staging/v1p5beta1/README.rst | 49 - .../v1p5beta1/docs/_static/custom.css | 3 - .../docs/asset_v1p5beta1/asset_service.rst | 10 - .../docs/asset_v1p5beta1/services.rst | 6 - .../v1p5beta1/docs/asset_v1p5beta1/types.rst | 6 - owl-bot-staging/v1p5beta1/docs/conf.py | 376 - owl-bot-staging/v1p5beta1/docs/index.rst | 7 - .../v1p5beta1/google/cloud/asset/__init__.py | 37 - .../google/cloud/asset/gapic_version.py | 16 - .../v1p5beta1/google/cloud/asset/py.typed | 2 - .../google/cloud/asset_v1p5beta1/__init__.py | 38 - .../cloud/asset_v1p5beta1/gapic_metadata.json | 43 - .../cloud/asset_v1p5beta1/gapic_version.py | 16 - .../google/cloud/asset_v1p5beta1/py.typed | 2 - .../asset_v1p5beta1/services/__init__.py | 15 - .../services/asset_service/__init__.py | 22 - .../services/asset_service/async_client.py | 330 - .../services/asset_service/client.py | 558 - .../services/asset_service/pagers.py | 140 - .../asset_service/transports/__init__.py | 38 - .../services/asset_service/transports/base.py | 156 - .../services/asset_service/transports/grpc.py | 266 - .../asset_service/transports/grpc_asyncio.py | 265 - .../services/asset_service/transports/rest.py | 289 - .../cloud/asset_v1p5beta1/types/__init__.py | 32 - .../asset_v1p5beta1/types/asset_service.py | 179 - .../cloud/asset_v1p5beta1/types/assets.py | 235 - owl-bot-staging/v1p5beta1/mypy.ini | 3 - owl-bot-staging/v1p5beta1/noxfile.py | 184 - ...nerated_asset_service_list_assets_async.py | 53 - ...enerated_asset_service_list_assets_sync.py | 53 - ...metadata_google.cloud.asset.v1p5beta1.json | 176 - .../scripts/fixup_asset_v1p5beta1_keywords.py | 176 - owl-bot-staging/v1p5beta1/setup.py | 91 - .../v1p5beta1/testing/constraints-3.10.txt | 7 - .../v1p5beta1/testing/constraints-3.11.txt | 7 - .../v1p5beta1/testing/constraints-3.12.txt | 7 - .../v1p5beta1/testing/constraints-3.7.txt | 10 - .../v1p5beta1/testing/constraints-3.8.txt | 7 - .../v1p5beta1/testing/constraints-3.9.txt | 7 - owl-bot-staging/v1p5beta1/tests/__init__.py | 16 - .../v1p5beta1/tests/unit/__init__.py | 16 - .../v1p5beta1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/asset_v1p5beta1/__init__.py | 16 - .../asset_v1p5beta1/test_asset_service.py | 1988 --- .../unit/gapic/asset_v1/test_asset_service.py | 454 +- .../asset_v1p1beta1/test_asset_service.py | 32 +- .../asset_v1p2beta1/test_asset_service.py | 60 +- .../asset_v1p5beta1/test_asset_service.py | 15 +- 249 files changed, 348 insertions(+), 64651 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/_static/custom.css delete mode 100644 owl-bot-staging/v1/docs/asset_v1/asset_service.rst delete mode 100644 owl-bot-staging/v1/docs/asset_v1/services.rst delete mode 100644 owl-bot-staging/v1/docs/asset_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/asset/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/py.typed delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py delete mode 100644 owl-bot-staging/v1/google/cloud/asset_v1/types/assets.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/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py delete mode 100644 owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json delete mode 100644 owl-bot-staging/v1/scripts/fixup_asset_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/asset_v1/__init__.py delete mode 100644 owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py delete mode 100644 owl-bot-staging/v1p1beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p1beta1/.flake8 delete mode 100644 owl-bot-staging/v1p1beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p1beta1/README.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst delete mode 100644 owl-bot-staging/v1p1beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p1beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py delete mode 100644 owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py delete mode 100644 owl-bot-staging/v1p1beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p1beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py delete mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py delete mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py delete mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py delete mode 100644 owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json delete mode 100644 owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py delete mode 100644 owl-bot-staging/v1p1beta1/setup.py delete mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1p1beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1p1beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py delete mode 100644 owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py delete mode 100644 owl-bot-staging/v1p2beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p2beta1/.flake8 delete mode 100644 owl-bot-staging/v1p2beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p2beta1/README.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst delete mode 100644 owl-bot-staging/v1p2beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p2beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py delete mode 100644 owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py delete mode 100644 owl-bot-staging/v1p2beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p2beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py delete mode 100644 owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json delete mode 100644 owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py delete mode 100644 owl-bot-staging/v1p2beta1/setup.py delete mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1p2beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1p2beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py delete mode 100644 owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py delete mode 100644 owl-bot-staging/v1p5beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p5beta1/.flake8 delete mode 100644 owl-bot-staging/v1p5beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p5beta1/README.rst delete mode 100644 owl-bot-staging/v1p5beta1/docs/_static/custom.css delete mode 100644 owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst delete mode 100644 owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst delete mode 100644 owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst delete mode 100644 owl-bot-staging/v1p5beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p5beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py delete mode 100644 owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py delete mode 100644 owl-bot-staging/v1p5beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p5beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py delete mode 100644 owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py delete mode 100644 owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json delete mode 100644 owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py delete mode 100644 owl-bot-staging/v1p5beta1/setup.py delete mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/v1p5beta1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/v1p5beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py delete mode 100644 owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 801f6d8a..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py - google/cloud/asset/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 29227d4c..00000000 --- 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 5c97e276..00000000 --- a/owl-bot-staging/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/asset *.py -recursive-include google/cloud/asset_v1 *.py diff --git a/owl-bot-staging/v1/README.rst b/owl-bot-staging/v1/README.rst deleted file mode 100644 index 110d4086..00000000 --- a/owl-bot-staging/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Asset 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 Asset 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/_static/custom.css b/owl-bot-staging/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0..00000000 --- a/owl-bot-staging/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/v1/docs/asset_v1/asset_service.rst b/owl-bot-staging/v1/docs/asset_v1/asset_service.rst deleted file mode 100644 index b2f80a4b..00000000 --- a/owl-bot-staging/v1/docs/asset_v1/asset_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -AssetService ------------------------------- - -.. automodule:: google.cloud.asset_v1.services.asset_service - :members: - :inherited-members: - -.. automodule:: google.cloud.asset_v1.services.asset_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1/docs/asset_v1/services.rst b/owl-bot-staging/v1/docs/asset_v1/services.rst deleted file mode 100644 index a5ddb91f..00000000 --- a/owl-bot-staging/v1/docs/asset_v1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Asset v1 API -====================================== -.. toctree:: - :maxdepth: 2 - - asset_service diff --git a/owl-bot-staging/v1/docs/asset_v1/types.rst b/owl-bot-staging/v1/docs/asset_v1/types.rst deleted file mode 100644 index 750d9c16..00000000 --- a/owl-bot-staging/v1/docs/asset_v1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Asset v1 API -=================================== - -.. automodule:: google.cloud.asset_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 b6b4f094..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-asset 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-asset" -copyright = u"2023, 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 = 'en' - -# 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-asset-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-asset.tex", - u"google-cloud-asset 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-asset", - u"Google Cloud Asset 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-asset", - u"google-cloud-asset Documentation", - author, - "google-cloud-asset", - "GAPIC library for Google Cloud Asset 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 fee6608e..00000000 --- a/owl-bot-staging/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - asset_v1/services - asset_v1/types diff --git a/owl-bot-staging/v1/google/cloud/asset/__init__.py b/owl-bot-staging/v1/google/cloud/asset/__init__.py deleted file mode 100644 index 40c78b1c..00000000 --- a/owl-bot-staging/v1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,185 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.asset_v1.services.asset_service.client import AssetServiceClient -from google.cloud.asset_v1.services.asset_service.async_client import AssetServiceAsyncClient - -from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyLongrunningMetadata -from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyLongrunningRequest -from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyLongrunningResponse -from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyRequest -from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyResponse -from google.cloud.asset_v1.types.asset_service import AnalyzeMoveRequest -from google.cloud.asset_v1.types.asset_service import AnalyzeMoveResponse -from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPoliciesRequest -from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPoliciesResponse -from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedAssetsRequest -from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedAssetsResponse -from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedContainersRequest -from google.cloud.asset_v1.types.asset_service import AnalyzeOrgPolicyGovernedContainersResponse -from google.cloud.asset_v1.types.asset_service import AnalyzerOrgPolicy -from google.cloud.asset_v1.types.asset_service import AnalyzerOrgPolicyConstraint -from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryRequest -from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryResponse -from google.cloud.asset_v1.types.asset_service import BatchGetEffectiveIamPoliciesRequest -from google.cloud.asset_v1.types.asset_service import BatchGetEffectiveIamPoliciesResponse -from google.cloud.asset_v1.types.asset_service import BigQueryDestination -from google.cloud.asset_v1.types.asset_service import CreateFeedRequest -from google.cloud.asset_v1.types.asset_service import CreateSavedQueryRequest -from google.cloud.asset_v1.types.asset_service import DeleteFeedRequest -from google.cloud.asset_v1.types.asset_service import DeleteSavedQueryRequest -from google.cloud.asset_v1.types.asset_service import ExportAssetsRequest -from google.cloud.asset_v1.types.asset_service import ExportAssetsResponse -from google.cloud.asset_v1.types.asset_service import Feed -from google.cloud.asset_v1.types.asset_service import FeedOutputConfig -from google.cloud.asset_v1.types.asset_service import GcsDestination -from google.cloud.asset_v1.types.asset_service import GcsOutputResult -from google.cloud.asset_v1.types.asset_service import GetFeedRequest -from google.cloud.asset_v1.types.asset_service import GetSavedQueryRequest -from google.cloud.asset_v1.types.asset_service import IamPolicyAnalysisOutputConfig -from google.cloud.asset_v1.types.asset_service import IamPolicyAnalysisQuery -from google.cloud.asset_v1.types.asset_service import ListAssetsRequest -from google.cloud.asset_v1.types.asset_service import ListAssetsResponse -from google.cloud.asset_v1.types.asset_service import ListFeedsRequest -from google.cloud.asset_v1.types.asset_service import ListFeedsResponse -from google.cloud.asset_v1.types.asset_service import ListSavedQueriesRequest -from google.cloud.asset_v1.types.asset_service import ListSavedQueriesResponse -from google.cloud.asset_v1.types.asset_service import MoveAnalysis -from google.cloud.asset_v1.types.asset_service import MoveAnalysisResult -from google.cloud.asset_v1.types.asset_service import MoveImpact -from google.cloud.asset_v1.types.asset_service import OutputConfig -from google.cloud.asset_v1.types.asset_service import OutputResult -from google.cloud.asset_v1.types.asset_service import PartitionSpec -from google.cloud.asset_v1.types.asset_service import PubsubDestination -from google.cloud.asset_v1.types.asset_service import QueryAssetsOutputConfig -from google.cloud.asset_v1.types.asset_service import QueryAssetsRequest -from google.cloud.asset_v1.types.asset_service import QueryAssetsResponse -from google.cloud.asset_v1.types.asset_service import QueryResult -from google.cloud.asset_v1.types.asset_service import SavedQuery -from google.cloud.asset_v1.types.asset_service import SearchAllIamPoliciesRequest -from google.cloud.asset_v1.types.asset_service import SearchAllIamPoliciesResponse -from google.cloud.asset_v1.types.asset_service import SearchAllResourcesRequest -from google.cloud.asset_v1.types.asset_service import SearchAllResourcesResponse -from google.cloud.asset_v1.types.asset_service import TableFieldSchema -from google.cloud.asset_v1.types.asset_service import TableSchema -from google.cloud.asset_v1.types.asset_service import UpdateFeedRequest -from google.cloud.asset_v1.types.asset_service import UpdateSavedQueryRequest -from google.cloud.asset_v1.types.asset_service import ContentType -from google.cloud.asset_v1.types.assets import Asset -from google.cloud.asset_v1.types.assets import AttachedResource -from google.cloud.asset_v1.types.assets import ConditionEvaluation -from google.cloud.asset_v1.types.assets import EffectiveTagDetails -from google.cloud.asset_v1.types.assets import IamPolicyAnalysisResult -from google.cloud.asset_v1.types.assets import IamPolicyAnalysisState -from google.cloud.asset_v1.types.assets import IamPolicySearchResult -from google.cloud.asset_v1.types.assets import RelatedAsset -from google.cloud.asset_v1.types.assets import RelatedAssets -from google.cloud.asset_v1.types.assets import RelatedResource -from google.cloud.asset_v1.types.assets import RelatedResources -from google.cloud.asset_v1.types.assets import RelationshipAttributes -from google.cloud.asset_v1.types.assets import Resource -from google.cloud.asset_v1.types.assets import ResourceSearchResult -from google.cloud.asset_v1.types.assets import Tag -from google.cloud.asset_v1.types.assets import TemporalAsset -from google.cloud.asset_v1.types.assets import TimeWindow -from google.cloud.asset_v1.types.assets import VersionedResource - -__all__ = ('AssetServiceClient', - 'AssetServiceAsyncClient', - 'AnalyzeIamPolicyLongrunningMetadata', - 'AnalyzeIamPolicyLongrunningRequest', - 'AnalyzeIamPolicyLongrunningResponse', - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'AnalyzeMoveRequest', - 'AnalyzeMoveResponse', - 'AnalyzeOrgPoliciesRequest', - 'AnalyzeOrgPoliciesResponse', - 'AnalyzeOrgPolicyGovernedAssetsRequest', - 'AnalyzeOrgPolicyGovernedAssetsResponse', - 'AnalyzeOrgPolicyGovernedContainersRequest', - 'AnalyzeOrgPolicyGovernedContainersResponse', - 'AnalyzerOrgPolicy', - 'AnalyzerOrgPolicyConstraint', - 'BatchGetAssetsHistoryRequest', - 'BatchGetAssetsHistoryResponse', - 'BatchGetEffectiveIamPoliciesRequest', - 'BatchGetEffectiveIamPoliciesResponse', - 'BigQueryDestination', - 'CreateFeedRequest', - 'CreateSavedQueryRequest', - 'DeleteFeedRequest', - 'DeleteSavedQueryRequest', - 'ExportAssetsRequest', - 'ExportAssetsResponse', - 'Feed', - 'FeedOutputConfig', - 'GcsDestination', - 'GcsOutputResult', - 'GetFeedRequest', - 'GetSavedQueryRequest', - 'IamPolicyAnalysisOutputConfig', - 'IamPolicyAnalysisQuery', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'ListSavedQueriesRequest', - 'ListSavedQueriesResponse', - 'MoveAnalysis', - 'MoveAnalysisResult', - 'MoveImpact', - 'OutputConfig', - 'OutputResult', - 'PartitionSpec', - 'PubsubDestination', - 'QueryAssetsOutputConfig', - 'QueryAssetsRequest', - 'QueryAssetsResponse', - 'QueryResult', - 'SavedQuery', - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'TableFieldSchema', - 'TableSchema', - 'UpdateFeedRequest', - 'UpdateSavedQueryRequest', - 'ContentType', - 'Asset', - 'AttachedResource', - 'ConditionEvaluation', - 'EffectiveTagDetails', - 'IamPolicyAnalysisResult', - 'IamPolicyAnalysisState', - 'IamPolicySearchResult', - 'RelatedAsset', - 'RelatedAssets', - 'RelatedResource', - 'RelatedResources', - 'RelationshipAttributes', - 'Resource', - 'ResourceSearchResult', - 'Tag', - 'TemporalAsset', - 'TimeWindow', - 'VersionedResource', -) diff --git a/owl-bot-staging/v1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1/google/cloud/asset/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1/google/cloud/asset/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/asset/py.typed b/owl-bot-staging/v1/google/cloud/asset/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1/google/cloud/asset/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py deleted file mode 100644 index 98cd9a11..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py +++ /dev/null @@ -1,186 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.asset_service import AssetServiceClient -from .services.asset_service import AssetServiceAsyncClient - -from .types.asset_service import AnalyzeIamPolicyLongrunningMetadata -from .types.asset_service import AnalyzeIamPolicyLongrunningRequest -from .types.asset_service import AnalyzeIamPolicyLongrunningResponse -from .types.asset_service import AnalyzeIamPolicyRequest -from .types.asset_service import AnalyzeIamPolicyResponse -from .types.asset_service import AnalyzeMoveRequest -from .types.asset_service import AnalyzeMoveResponse -from .types.asset_service import AnalyzeOrgPoliciesRequest -from .types.asset_service import AnalyzeOrgPoliciesResponse -from .types.asset_service import AnalyzeOrgPolicyGovernedAssetsRequest -from .types.asset_service import AnalyzeOrgPolicyGovernedAssetsResponse -from .types.asset_service import AnalyzeOrgPolicyGovernedContainersRequest -from .types.asset_service import AnalyzeOrgPolicyGovernedContainersResponse -from .types.asset_service import AnalyzerOrgPolicy -from .types.asset_service import AnalyzerOrgPolicyConstraint -from .types.asset_service import BatchGetAssetsHistoryRequest -from .types.asset_service import BatchGetAssetsHistoryResponse -from .types.asset_service import BatchGetEffectiveIamPoliciesRequest -from .types.asset_service import BatchGetEffectiveIamPoliciesResponse -from .types.asset_service import BigQueryDestination -from .types.asset_service import CreateFeedRequest -from .types.asset_service import CreateSavedQueryRequest -from .types.asset_service import DeleteFeedRequest -from .types.asset_service import DeleteSavedQueryRequest -from .types.asset_service import ExportAssetsRequest -from .types.asset_service import ExportAssetsResponse -from .types.asset_service import Feed -from .types.asset_service import FeedOutputConfig -from .types.asset_service import GcsDestination -from .types.asset_service import GcsOutputResult -from .types.asset_service import GetFeedRequest -from .types.asset_service import GetSavedQueryRequest -from .types.asset_service import IamPolicyAnalysisOutputConfig -from .types.asset_service import IamPolicyAnalysisQuery -from .types.asset_service import ListAssetsRequest -from .types.asset_service import ListAssetsResponse -from .types.asset_service import ListFeedsRequest -from .types.asset_service import ListFeedsResponse -from .types.asset_service import ListSavedQueriesRequest -from .types.asset_service import ListSavedQueriesResponse -from .types.asset_service import MoveAnalysis -from .types.asset_service import MoveAnalysisResult -from .types.asset_service import MoveImpact -from .types.asset_service import OutputConfig -from .types.asset_service import OutputResult -from .types.asset_service import PartitionSpec -from .types.asset_service import PubsubDestination -from .types.asset_service import QueryAssetsOutputConfig -from .types.asset_service import QueryAssetsRequest -from .types.asset_service import QueryAssetsResponse -from .types.asset_service import QueryResult -from .types.asset_service import SavedQuery -from .types.asset_service import SearchAllIamPoliciesRequest -from .types.asset_service import SearchAllIamPoliciesResponse -from .types.asset_service import SearchAllResourcesRequest -from .types.asset_service import SearchAllResourcesResponse -from .types.asset_service import TableFieldSchema -from .types.asset_service import TableSchema -from .types.asset_service import UpdateFeedRequest -from .types.asset_service import UpdateSavedQueryRequest -from .types.asset_service import ContentType -from .types.assets import Asset -from .types.assets import AttachedResource -from .types.assets import ConditionEvaluation -from .types.assets import EffectiveTagDetails -from .types.assets import IamPolicyAnalysisResult -from .types.assets import IamPolicyAnalysisState -from .types.assets import IamPolicySearchResult -from .types.assets import RelatedAsset -from .types.assets import RelatedAssets -from .types.assets import RelatedResource -from .types.assets import RelatedResources -from .types.assets import RelationshipAttributes -from .types.assets import Resource -from .types.assets import ResourceSearchResult -from .types.assets import Tag -from .types.assets import TemporalAsset -from .types.assets import TimeWindow -from .types.assets import VersionedResource - -__all__ = ( - 'AssetServiceAsyncClient', -'AnalyzeIamPolicyLongrunningMetadata', -'AnalyzeIamPolicyLongrunningRequest', -'AnalyzeIamPolicyLongrunningResponse', -'AnalyzeIamPolicyRequest', -'AnalyzeIamPolicyResponse', -'AnalyzeMoveRequest', -'AnalyzeMoveResponse', -'AnalyzeOrgPoliciesRequest', -'AnalyzeOrgPoliciesResponse', -'AnalyzeOrgPolicyGovernedAssetsRequest', -'AnalyzeOrgPolicyGovernedAssetsResponse', -'AnalyzeOrgPolicyGovernedContainersRequest', -'AnalyzeOrgPolicyGovernedContainersResponse', -'AnalyzerOrgPolicy', -'AnalyzerOrgPolicyConstraint', -'Asset', -'AssetServiceClient', -'AttachedResource', -'BatchGetAssetsHistoryRequest', -'BatchGetAssetsHistoryResponse', -'BatchGetEffectiveIamPoliciesRequest', -'BatchGetEffectiveIamPoliciesResponse', -'BigQueryDestination', -'ConditionEvaluation', -'ContentType', -'CreateFeedRequest', -'CreateSavedQueryRequest', -'DeleteFeedRequest', -'DeleteSavedQueryRequest', -'EffectiveTagDetails', -'ExportAssetsRequest', -'ExportAssetsResponse', -'Feed', -'FeedOutputConfig', -'GcsDestination', -'GcsOutputResult', -'GetFeedRequest', -'GetSavedQueryRequest', -'IamPolicyAnalysisOutputConfig', -'IamPolicyAnalysisQuery', -'IamPolicyAnalysisResult', -'IamPolicyAnalysisState', -'IamPolicySearchResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFeedsRequest', -'ListFeedsResponse', -'ListSavedQueriesRequest', -'ListSavedQueriesResponse', -'MoveAnalysis', -'MoveAnalysisResult', -'MoveImpact', -'OutputConfig', -'OutputResult', -'PartitionSpec', -'PubsubDestination', -'QueryAssetsOutputConfig', -'QueryAssetsRequest', -'QueryAssetsResponse', -'QueryResult', -'RelatedAsset', -'RelatedAssets', -'RelatedResource', -'RelatedResources', -'RelationshipAttributes', -'Resource', -'ResourceSearchResult', -'SavedQuery', -'SearchAllIamPoliciesRequest', -'SearchAllIamPoliciesResponse', -'SearchAllResourcesRequest', -'SearchAllResourcesResponse', -'TableFieldSchema', -'TableSchema', -'Tag', -'TemporalAsset', -'TimeWindow', -'UpdateFeedRequest', -'UpdateSavedQueryRequest', -'VersionedResource', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json b/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json deleted file mode 100644 index e39e5043..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json +++ /dev/null @@ -1,373 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.asset_v1", - "protoPackage": "google.cloud.asset.v1", - "schema": "1.0", - "services": { - "AssetService": { - "clients": { - "grpc": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "AnalyzeIamPolicy": { - "methods": [ - "analyze_iam_policy" - ] - }, - "AnalyzeIamPolicyLongrunning": { - "methods": [ - "analyze_iam_policy_longrunning" - ] - }, - "AnalyzeMove": { - "methods": [ - "analyze_move" - ] - }, - "AnalyzeOrgPolicies": { - "methods": [ - "analyze_org_policies" - ] - }, - "AnalyzeOrgPolicyGovernedAssets": { - "methods": [ - "analyze_org_policy_governed_assets" - ] - }, - "AnalyzeOrgPolicyGovernedContainers": { - "methods": [ - "analyze_org_policy_governed_containers" - ] - }, - "BatchGetAssetsHistory": { - "methods": [ - "batch_get_assets_history" - ] - }, - "BatchGetEffectiveIamPolicies": { - "methods": [ - "batch_get_effective_iam_policies" - ] - }, - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "CreateSavedQuery": { - "methods": [ - "create_saved_query" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "DeleteSavedQuery": { - "methods": [ - "delete_saved_query" - ] - }, - "ExportAssets": { - "methods": [ - "export_assets" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "GetSavedQuery": { - "methods": [ - "get_saved_query" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "ListSavedQueries": { - "methods": [ - "list_saved_queries" - ] - }, - "QueryAssets": { - "methods": [ - "query_assets" - ] - }, - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - }, - "UpdateSavedQuery": { - "methods": [ - "update_saved_query" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AssetServiceAsyncClient", - "rpcs": { - "AnalyzeIamPolicy": { - "methods": [ - "analyze_iam_policy" - ] - }, - "AnalyzeIamPolicyLongrunning": { - "methods": [ - "analyze_iam_policy_longrunning" - ] - }, - "AnalyzeMove": { - "methods": [ - "analyze_move" - ] - }, - "AnalyzeOrgPolicies": { - "methods": [ - "analyze_org_policies" - ] - }, - "AnalyzeOrgPolicyGovernedAssets": { - "methods": [ - "analyze_org_policy_governed_assets" - ] - }, - "AnalyzeOrgPolicyGovernedContainers": { - "methods": [ - "analyze_org_policy_governed_containers" - ] - }, - "BatchGetAssetsHistory": { - "methods": [ - "batch_get_assets_history" - ] - }, - "BatchGetEffectiveIamPolicies": { - "methods": [ - "batch_get_effective_iam_policies" - ] - }, - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "CreateSavedQuery": { - "methods": [ - "create_saved_query" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "DeleteSavedQuery": { - "methods": [ - "delete_saved_query" - ] - }, - "ExportAssets": { - "methods": [ - "export_assets" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "GetSavedQuery": { - "methods": [ - "get_saved_query" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "ListSavedQueries": { - "methods": [ - "list_saved_queries" - ] - }, - "QueryAssets": { - "methods": [ - "query_assets" - ] - }, - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - }, - "UpdateSavedQuery": { - "methods": [ - "update_saved_query" - ] - } - } - }, - "rest": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "AnalyzeIamPolicy": { - "methods": [ - "analyze_iam_policy" - ] - }, - "AnalyzeIamPolicyLongrunning": { - "methods": [ - "analyze_iam_policy_longrunning" - ] - }, - "AnalyzeMove": { - "methods": [ - "analyze_move" - ] - }, - "AnalyzeOrgPolicies": { - "methods": [ - "analyze_org_policies" - ] - }, - "AnalyzeOrgPolicyGovernedAssets": { - "methods": [ - "analyze_org_policy_governed_assets" - ] - }, - "AnalyzeOrgPolicyGovernedContainers": { - "methods": [ - "analyze_org_policy_governed_containers" - ] - }, - "BatchGetAssetsHistory": { - "methods": [ - "batch_get_assets_history" - ] - }, - "BatchGetEffectiveIamPolicies": { - "methods": [ - "batch_get_effective_iam_policies" - ] - }, - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "CreateSavedQuery": { - "methods": [ - "create_saved_query" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "DeleteSavedQuery": { - "methods": [ - "delete_saved_query" - ] - }, - "ExportAssets": { - "methods": [ - "export_assets" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "GetSavedQuery": { - "methods": [ - "get_saved_query" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "ListSavedQueries": { - "methods": [ - "list_saved_queries" - ] - }, - "QueryAssets": { - "methods": [ - "query_assets" - ] - }, - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - }, - "UpdateSavedQuery": { - "methods": [ - "update_saved_query" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py b/owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/py.typed b/owl-bot-staging/v1/google/cloud/asset_v1/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py deleted file mode 100644 index 89a37dc9..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py deleted file mode 100644 index 542f923f..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AssetServiceClient -from .async_client import AssetServiceAsyncClient - -__all__ = ( - 'AssetServiceClient', - 'AssetServiceAsyncClient', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py deleted file mode 100644 index 58f650d9..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py +++ /dev/null @@ -1,3169 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.asset_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.asset_v1.services.asset_service import pagers -from google.cloud.asset_v1.types import asset_service -from google.cloud.asset_v1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .client import AssetServiceClient - - -class AssetServiceAsyncClient: - """Asset service definition.""" - - _client: AssetServiceClient - - DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT - - access_level_path = staticmethod(AssetServiceClient.access_level_path) - parse_access_level_path = staticmethod(AssetServiceClient.parse_access_level_path) - access_policy_path = staticmethod(AssetServiceClient.access_policy_path) - parse_access_policy_path = staticmethod(AssetServiceClient.parse_access_policy_path) - asset_path = staticmethod(AssetServiceClient.asset_path) - parse_asset_path = staticmethod(AssetServiceClient.parse_asset_path) - feed_path = staticmethod(AssetServiceClient.feed_path) - parse_feed_path = staticmethod(AssetServiceClient.parse_feed_path) - inventory_path = staticmethod(AssetServiceClient.inventory_path) - parse_inventory_path = staticmethod(AssetServiceClient.parse_inventory_path) - saved_query_path = staticmethod(AssetServiceClient.saved_query_path) - parse_saved_query_path = staticmethod(AssetServiceClient.parse_saved_query_path) - service_perimeter_path = staticmethod(AssetServiceClient.service_perimeter_path) - parse_service_perimeter_path = staticmethod(AssetServiceClient.parse_service_perimeter_path) - common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AssetServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AssetServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AssetServiceClient.common_project_path) - parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) - common_location_path = staticmethod(AssetServiceClient.common_location_path) - parse_common_location_path = staticmethod(AssetServiceClient.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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def export_assets(self, - request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports assets with time and resource types to a given Cloud - Storage location/BigQuery table. For Cloud Storage location - destinations, the output format is newline-delimited JSON. Each - line represents a - [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in - the JSON format; for BigQuery table destinations, the output - table stores the fields in asset Protobuf as columns. This API - implements the - [google.longrunning.Operation][google.longrunning.Operation] - API, which allows you to keep track of the export. We recommend - intervals of at least 2 seconds with exponential retry to poll - the export operation result. For regular-size resource parent, - the export operation usually finishes within 5 minutes. - - .. 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 asset_v1 - - async def sample_export_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - output_config = asset_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.ExportAssetsRequest( - parent="parent_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_assets(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.ExportAssetsRequest, dict]]): - The request object. Export asset request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.ExportAssetsResponse` The export asset response. This message is returned by the - [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] - method in the returned - [google.longrunning.Operation.response][google.longrunning.Operation.response] - field. - - """ - # Create or coerce a protobuf request object. - request = asset_service.ExportAssetsRequest(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.export_assets, - 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, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - asset_service.ExportAssetsResponse, - metadata_type=asset_service.ExportAssetsRequest, - ) - - # Done; return the response. - return response - - async def list_assets(self, - request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsAsyncPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - .. 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 asset_v1 - - async def sample_list_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.ListAssetsRequest, dict]]): - The request object. ListAssets request. - parent (:class:`str`): - Required. Name of the organization, folder, or project - the assets belong to. Format: - "organizations/[organization-number]" (such as - "organizations/123"), "projects/[project-id]" (such as - "projects/my-project-id"), "projects/[project-number]" - (such as "projects/12345"), or "folders/[folder-number]" - (such as "folders/12345"). - - 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.asset_v1.services.asset_service.pagers.ListAssetsAsyncPager: - ListAssets response. - - 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 = asset_service.ListAssetsRequest(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_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def batch_get_assets_history(self, - request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: - r"""Batch gets the update history of assets that overlap a time - window. For IAM_POLICY content, this API outputs history when - the asset and its attached IAM POLICY both exist. This can - create gaps in the output history. Otherwise, this API outputs - history with asset in both non-delete or deleted status. If a - specified asset does not exist, this API returns an - INVALID_ARGUMENT error. - - .. 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 asset_v1 - - async def sample_batch_get_assets_history(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetAssetsHistoryRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_get_assets_history(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest, dict]]): - The request object. Batch get assets history request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.BatchGetAssetsHistoryResponse: - Batch get assets history response. - """ - # Create or coerce a protobuf request object. - request = asset_service.BatchGetAssetsHistoryRequest(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.batch_get_assets_history, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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 create_feed(self, - request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - .. 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 asset_v1 - - async def sample_create_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = await client.create_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.CreateFeedRequest, dict]]): - The request object. Create asset feed request. - parent (:class:`str`): - Required. The name of the - project/folder/organization where this - feed should be created in. It can only - be an organization number (such as - "organizations/123"), a folder number - (such as "folders/123"), a project ID - (such as "projects/my-project-id"), or a - project number (such as - "projects/12345"). - - 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.asset_v1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - # 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 = asset_service.CreateFeedRequest(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.create_feed, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_feed(self, - request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - .. 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 asset_v1 - - async def sample_get_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = await client.get_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.GetFeedRequest, dict]]): - The request object. Get asset feed request. - name (:class:`str`): - Required. The name of the Feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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.asset_v1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - # 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 = asset_service.GetFeedRequest(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_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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_feeds(self, - request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - .. 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 asset_v1 - - async def sample_list_feeds(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_feeds(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.ListFeedsRequest, dict]]): - The request object. List asset feeds request. - parent (:class:`str`): - Required. The parent - project/folder/organization whose feeds - are to be listed. It can only be using - project/folder/organization number (such - as "folders/12345")", or a project ID - (such as "projects/my-project-id"). - - 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.asset_v1.types.ListFeedsResponse: - - """ - # 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 = asset_service.ListFeedsRequest(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_feeds, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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_feed(self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - .. 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 asset_v1 - - async def sample_update_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = await client.update_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.UpdateFeedRequest, dict]]): - The request object. Update asset feed request. - feed (:class:`google.cloud.asset_v1.types.Feed`): - Required. The new values of feed details. It must match - an existing feed and the field ``name`` must be in the - format of: projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - - This corresponds to the ``feed`` 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.asset_v1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - # 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([feed]) - 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 = asset_service.UpdateFeedRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if feed is not None: - request.feed = feed - - # 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_feed, - 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(( - ("feed.name", request.feed.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_feed(self, - request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. - - .. 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 asset_v1 - - async def sample_delete_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - await client.delete_feed(request=request) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.DeleteFeedRequest, dict]]): - The request object. - name (:class:`str`): - Required. The name of the feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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 = asset_service.DeleteFeedRequest(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_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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 search_all_resources(self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesAsyncPager: - r"""Searches all Google Cloud resources within the specified scope, - such as a project, folder, or organization. The caller must be - granted the ``cloudasset.assets.searchAllResources`` permission - on the desired scope, otherwise the request will be rejected. - - .. 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 asset_v1 - - async def sample_search_all_resources(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.SearchAllResourcesRequest, dict]]): - The request object. Search all resources request. - scope (:class:`str`): - Required. A scope can be a project, a folder, or an - organization. The search is limited to the resources - within the ``scope``. The caller must be granted the - ```cloudasset.assets.searchAllResources`` `__ - permission on the desired scope. - - The allowed values are: - - - projects/{PROJECT_ID} (e.g., "projects/foo-bar") - - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") - - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`str`): - Optional. The query statement. See `how to construct a - query `__ - for more information. If not specified or empty, it will - search all the resources within the specified ``scope``. - - Examples: - - - ``name:Important`` to find Google Cloud resources - whose name contains ``Important`` as a word. - - ``name=Important`` to find the Google Cloud resource - whose name is exactly ``Important``. - - ``displayName:Impor*`` to find Google Cloud resources - whose display name contains ``Impor`` as a prefix of - any word in the field. - - ``location:us-west*`` to find Google Cloud resources - whose location contains both ``us`` and ``west`` as - prefixes. - - ``labels:prod`` to find Google Cloud resources whose - labels contain ``prod`` as a key or value. - - ``labels.env:prod`` to find Google Cloud resources - that have a label ``env`` and its value is ``prod``. - - ``labels.env:*`` to find Google Cloud resources that - have a label ``env``. - - ``tagKeys:env`` to find Google Cloud resources that - have directly attached tags where the - ```TagKey`` `__ - .\ ``namespacedName`` contains ``env``. - - ``tagValues:prod*`` to find Google Cloud resources - that have directly attached tags where the - ```TagValue`` `__ - .\ ``namespacedName`` contains a word prefixed by - ``prod``. - - ``tagValueIds=tagValues/123`` to find Google Cloud - resources that have directly attached tags where the - ```TagValue`` `__ - .\ ``name`` is exactly ``tagValues/123``. - - ``effectiveTagKeys:env`` to find Google Cloud - resources that have directly attached or inherited - tags where the - ```TagKey`` `__ - .\ ``namespacedName`` contains ``env``. - - ``effectiveTagValues:prod*`` to find Google Cloud - resources that have directly attached or inherited - tags where the - ```TagValue`` `__ - .\ ``namespacedName`` contains a word prefixed by - ``prod``. - - ``effectiveTagValueIds=tagValues/123`` to find Google - Cloud resources that have directly attached or - inherited tags where the - ```TagValue`` `__ - .\ ``name`` is exactly ``tagValues/123``. - - ``kmsKey:key`` to find Google Cloud resources - encrypted with a customer-managed encryption key - whose name contains ``key`` as a word. This field is - deprecated. Please use the ``kmsKeys`` field to - retrieve Cloud KMS key information. - - ``kmsKeys:key`` to find Google Cloud resources - encrypted with customer-managed encryption keys whose - name contains the word ``key``. - - ``relationships:instance-group-1`` to find Google - Cloud resources that have relationships with - ``instance-group-1`` in the related resource name. - - ``relationships:INSTANCE_TO_INSTANCEGROUP`` to find - Compute Engine instances that have relationships of - type ``INSTANCE_TO_INSTANCEGROUP``. - - ``relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1`` - to find Compute Engine instances that have - relationships with ``instance-group-1`` in the - Compute Engine instance group resource name, for - relationship type ``INSTANCE_TO_INSTANCEGROUP``. - - ``state:ACTIVE`` to find Google Cloud resources whose - state contains ``ACTIVE`` as a word. - - ``NOT state:ACTIVE`` to find Google Cloud resources - whose state doesn't contain ``ACTIVE`` as a word. - - ``createTime<1609459200`` to find Google Cloud - resources that were created before - ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the - epoch timestamp of ``2021-01-01 00:00:00 UTC`` in - seconds. - - ``updateTime>1609459200`` to find Google Cloud - resources that were updated after - ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the - epoch timestamp of ``2021-01-01 00:00:00 UTC`` in - seconds. - - ``Important`` to find Google Cloud resources that - contain ``Important`` as a word in any of the - searchable fields. - - ``Impor*`` to find Google Cloud resources that - contain ``Impor`` as a prefix of any word in any of - the searchable fields. - - ``Important location:(us-west1 OR global)`` to find - Google Cloud resources that contain ``Important`` as - a word in any of the searchable fields and are also - located in the ``us-west1`` region or the ``global`` - location. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - asset_types (:class:`MutableSequence[str]`): - Optional. A list of asset types that this request - searches for. If empty, it will search all the - `searchable asset - types `__. - - Regular expressions are also supported. For example: - - - "compute.googleapis.com.*" snapshots resources whose - asset type starts with "compute.googleapis.com". - - ".*Instance" snapshots resources whose asset type - ends with "Instance". - - ".*Instance.*" snapshots resources whose asset type - contains "Instance". - - See `RE2 `__ - for all supported regular expression syntax. If the - regular expression does not match any supported asset - type, an INVALID_ARGUMENT error will be returned. - - This corresponds to the ``asset_types`` 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.asset_v1.services.asset_service.pagers.SearchAllResourcesAsyncPager: - Search all resources response. - - 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([scope, query, asset_types]) - 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 = asset_service.SearchAllResourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - if asset_types: - request.asset_types.extend(asset_types) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_all_resources, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.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(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllResourcesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_all_iam_policies(self, - request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllIamPoliciesAsyncPager: - r"""Searches all IAM policies within the specified scope, such as a - project, folder, or organization. The caller must be granted the - ``cloudasset.assets.searchAllIamPolicies`` permission on the - desired scope, otherwise the request will be rejected. - - .. 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 asset_v1 - - async def sample_search_all_iam_policies(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.SearchAllIamPoliciesRequest, dict]]): - The request object. Search all IAM policies request. - scope (:class:`str`): - Required. A scope can be a project, a folder, or an - organization. The search is limited to the IAM policies - within the ``scope``. The caller must be granted the - ```cloudasset.assets.searchAllIamPolicies`` `__ - permission on the desired scope. - - The allowed values are: - - - projects/{PROJECT_ID} (e.g., "projects/foo-bar") - - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") - - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`str`): - Optional. The query statement. See `how to construct a - query `__ - for more information. If not specified or empty, it will - search all the IAM policies within the specified - ``scope``. Note that the query string is compared - against each IAM policy binding, including its - principals, roles, and IAM conditions. The returned IAM - policies will only contain the bindings that match your - query. To learn more about the IAM policy structure, see - the `IAM policy - documentation `__. - - Examples: - - - ``policy:amy@gmail.com`` to find IAM policy bindings - that specify user "amy@gmail.com". - - ``policy:roles/compute.admin`` to find IAM policy - bindings that specify the Compute Admin role. - - ``policy:comp*`` to find IAM policy bindings that - contain "comp" as a prefix of any word in the - binding. - - ``policy.role.permissions:storage.buckets.update`` to - find IAM policy bindings that specify a role - containing "storage.buckets.update" permission. Note - that if callers don't have ``iam.roles.get`` access - to a role's included permissions, policy bindings - that specify this role will be dropped from the - search results. - - ``policy.role.permissions:upd*`` to find IAM policy - bindings that specify a role containing "upd" as a - prefix of any word in the role permission. Note that - if callers don't have ``iam.roles.get`` access to a - role's included permissions, policy bindings that - specify this role will be dropped from the search - results. - - ``resource:organizations/123456`` to find IAM policy - bindings that are set on "organizations/123456". - - ``resource=//cloudresourcemanager.googleapis.com/projects/myproject`` - to find IAM policy bindings that are set on the - project named "myproject". - - ``Important`` to find IAM policy bindings that - contain "Important" as a word in any of the - searchable fields (except for the included - permissions). - - ``resource:(instance1 OR instance2) policy:amy`` to - find IAM policy bindings that are set on resources - "instance1" or "instance2" and also specify user - "amy". - - ``roles:roles/compute.admin`` to find IAM policy - bindings that specify the Compute Admin role. - - ``memberTypes:user`` to find IAM policy bindings that - contain the principal type "user". - - This corresponds to the ``query`` 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.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager: - Search all IAM policies response. - - 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([scope, query]) - 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 = asset_service.SearchAllIamPoliciesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_all_iam_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.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(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllIamPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_iam_policy(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: - r"""Analyzes IAM policies to answer which identities have - what accesses on which resources. - - .. 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 asset_v1 - - async def sample_analyze_iam_policy(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - request = asset_v1.AnalyzeIamPolicyRequest( - analysis_query=analysis_query, - ) - - # Make the request - response = await client.analyze_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.AnalyzeIamPolicyRequest, dict]]): - The request object. A request message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.AnalyzeIamPolicyResponse: - A response message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - - """ - # Create or coerce a protobuf request object. - request = asset_service.AnalyzeIamPolicyRequest(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.analyze_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.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(( - ("analysis_query.scope", request.analysis_query.scope), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_iam_policy_longrunning(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Analyzes IAM policies asynchronously to answer which identities - have what accesses on which resources, and writes the analysis - results to a Google Cloud Storage or a BigQuery destination. For - Cloud Storage destination, the output format is the JSON format - that represents a - [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. - This method implements the - [google.longrunning.Operation][google.longrunning.Operation], - which allows you to track the operation status. We recommend - intervals of at least 2 seconds with exponential backoff retry - to poll the operation result. The metadata contains the metadata - for the long-running operation. - - .. 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 asset_v1 - - async def sample_analyze_iam_policy_longrunning(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - output_config = asset_v1.IamPolicyAnalysisOutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.AnalyzeIamPolicyLongrunningRequest( - analysis_query=analysis_query, - output_config=output_config, - ) - - # Make the request - operation = client.analyze_iam_policy_longrunning(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest, dict]]): - The request object. A request message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.AnalyzeIamPolicyLongrunningResponse` A response message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - - """ - # Create or coerce a protobuf request object. - request = asset_service.AnalyzeIamPolicyLongrunningRequest(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.analyze_iam_policy_longrunning, - 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(( - ("analysis_query.scope", request.analysis_query.scope), - )), - ) - - # 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, - asset_service.AnalyzeIamPolicyLongrunningResponse, - metadata_type=asset_service.AnalyzeIamPolicyLongrunningMetadata, - ) - - # Done; return the response. - return response - - async def analyze_move(self, - request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeMoveResponse: - r"""Analyze moving a resource to a specified destination - without kicking off the actual move. The analysis is - best effort depending on the user's permissions of - viewing different hierarchical policies and - configurations. The policies and configuration are - subject to change before the actual resource migration - takes place. - - .. 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 asset_v1 - - async def sample_analyze_move(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeMoveRequest( - resource="resource_value", - destination_parent="destination_parent_value", - ) - - # Make the request - response = await client.analyze_move(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.AnalyzeMoveRequest, dict]]): - The request object. The request message for performing - resource move analysis. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.AnalyzeMoveResponse: - The response message for resource - move analysis. - - """ - # Create or coerce a protobuf request object. - request = asset_service.AnalyzeMoveRequest(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.analyze_move, - 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 query_assets(self, - request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.QueryAssetsResponse: - r"""Issue a job that queries assets using a SQL statement compatible - with `BigQuery - SQL `__. - - If the query execution finishes within timeout and there's no - pagination, the full query results will be returned in the - ``QueryAssetsResponse``. - - Otherwise, full query results can be obtained by issuing extra - requests with the ``job_reference`` from the a previous - ``QueryAssets`` call. - - Note, the query result has approximately 10 GB limitation - enforced by - `BigQuery `__. - Queries return larger results will result in errors. - - .. 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 asset_v1 - - async def sample_query_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.QueryAssetsRequest( - statement="statement_value", - parent="parent_value", - ) - - # Make the request - response = await client.query_assets(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.QueryAssetsRequest, dict]]): - The request object. QueryAssets request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.QueryAssetsResponse: - QueryAssets response. - """ - # Create or coerce a protobuf request object. - request = asset_service.QueryAssetsRequest(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.query_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=200.0, - ), - default_timeout=200.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 create_saved_query(self, - request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, - *, - parent: Optional[str] = None, - saved_query: Optional[asset_service.SavedQuery] = None, - saved_query_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.SavedQuery: - r"""Creates a saved query in a parent - project/folder/organization. - - .. 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 asset_v1 - - async def sample_create_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.CreateSavedQueryRequest( - parent="parent_value", - saved_query_id="saved_query_id_value", - ) - - # Make the request - response = await client.create_saved_query(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.CreateSavedQueryRequest, dict]]): - The request object. Request to create a saved query. - parent (:class:`str`): - Required. The name of the project/folder/organization - where this saved_query should be created in. It can only - be an organization number (such as "organizations/123"), - a folder number (such as "folders/123"), a project ID - (such as "projects/my-project-id"), or a project number - (such as "projects/12345"). - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - saved_query (:class:`google.cloud.asset_v1.types.SavedQuery`): - Required. The saved_query details. The ``name`` field - must be empty as it will be generated based on the - parent and saved_query_id. - - This corresponds to the ``saved_query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - saved_query_id (:class:`str`): - Required. The ID to use for the saved query, which must - be unique in the specified parent. It will become the - final component of the saved query's resource name. - - This value should be 4-63 characters, and valid - characters are ``[a-z][0-9]-``. - - Notice that this field is required in the saved query - creation, and the ``name`` field of the ``saved_query`` - will be ignored. - - This corresponds to the ``saved_query_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.asset_v1.types.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - # 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, saved_query, saved_query_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 = asset_service.CreateSavedQueryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if saved_query is not None: - request.saved_query = saved_query - if saved_query_id is not None: - request.saved_query_id = saved_query_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_saved_query, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_saved_query(self, - request: Optional[Union[asset_service.GetSavedQueryRequest, 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]] = (), - ) -> asset_service.SavedQuery: - r"""Gets details about a saved query. - - .. 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 asset_v1 - - async def sample_get_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.GetSavedQueryRequest( - name="name_value", - ) - - # Make the request - response = await client.get_saved_query(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.GetSavedQueryRequest, dict]]): - The request object. Request to get a saved query. - name (:class:`str`): - Required. The name of the saved query and it must be in - the format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - 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.asset_v1.types.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - # 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 = asset_service.GetSavedQueryRequest(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_saved_query, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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_saved_queries(self, - request: Optional[Union[asset_service.ListSavedQueriesRequest, 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.ListSavedQueriesAsyncPager: - r"""Lists all saved queries in a parent - project/folder/organization. - - .. 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 asset_v1 - - async def sample_list_saved_queries(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.ListSavedQueriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_saved_queries(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.ListSavedQueriesRequest, dict]]): - The request object. Request to list saved queries. - parent (:class:`str`): - Required. The parent - project/folder/organization whose - savedQueries are to be listed. It can - only be using - project/folder/organization number (such - as "folders/12345")", or a project ID - (such as "projects/my-project-id"). - - 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.asset_v1.services.asset_service.pagers.ListSavedQueriesAsyncPager: - Response of listing saved queries. - - 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 = asset_service.ListSavedQueriesRequest(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_saved_queries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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.ListSavedQueriesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_saved_query(self, - request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, - *, - saved_query: Optional[asset_service.SavedQuery] = 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]] = (), - ) -> asset_service.SavedQuery: - r"""Updates a saved query. - - .. 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 asset_v1 - - async def sample_update_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.UpdateSavedQueryRequest( - ) - - # Make the request - response = await client.update_saved_query(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.UpdateSavedQueryRequest, dict]]): - The request object. Request to update a saved query. - saved_query (:class:`google.cloud.asset_v1.types.SavedQuery`): - Required. The saved query to update. - - The saved query's ``name`` field is used to identify the - one to update, which has format as below: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - This corresponds to the ``saved_query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. The list of fields to - update. - - 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.asset_v1.types.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - # 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([saved_query, 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 = asset_service.UpdateSavedQueryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if saved_query is not None: - request.saved_query = saved_query - 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_saved_query, - 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(( - ("saved_query.name", request.saved_query.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_saved_query(self, - request: Optional[Union[asset_service.DeleteSavedQueryRequest, 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"""Deletes a saved query. - - .. 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 asset_v1 - - async def sample_delete_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.DeleteSavedQueryRequest( - name="name_value", - ) - - # Make the request - await client.delete_saved_query(request=request) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.DeleteSavedQueryRequest, dict]]): - The request object. Request to delete a saved query. - name (:class:`str`): - Required. The name of the saved query to delete. It must - be in the format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - 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 = asset_service.DeleteSavedQueryRequest(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_saved_query, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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 batch_get_effective_iam_policies(self, - request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: - r"""Gets effective IAM policies for a batch of resources. - - .. 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 asset_v1 - - async def sample_batch_get_effective_iam_policies(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetEffectiveIamPoliciesRequest( - scope="scope_value", - names=['names_value1', 'names_value2'], - ) - - # Make the request - response = await client.batch_get_effective_iam_policies(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest, dict]]): - The request object. A request message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.BatchGetEffectiveIamPoliciesResponse: - A response message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - - """ - # Create or coerce a protobuf request object. - request = asset_service.BatchGetEffectiveIamPoliciesRequest(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.batch_get_effective_iam_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.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(( - ("scope", request.scope), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_org_policies(self, - request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.AnalyzeOrgPoliciesAsyncPager: - r"""Analyzes organization policies under a scope. - - .. 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 asset_v1 - - async def sample_analyze_org_policies(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPoliciesRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest, dict]]): - The request object. A request message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - scope (:class:`str`): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - constraint (:class:`str`): - Required. The name of the constraint - to analyze organization policies for. - The response only contains analyzed - organization policies for the provided - constraint. - - This corresponds to the ``constraint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The expression to filter - [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. - The only supported field is - ``consolidated_policy.attached_resource``, and the only - supported operator is ``=``. - - Example: - consolidated_policy.attached_resource="//cloudresourcemanager.googleapis.com/folders/001" - will return the org policy results of"folders/001". - - This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesAsyncPager: - The response message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - - 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([scope, constraint, filter]) - 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 = asset_service.AnalyzeOrgPoliciesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if constraint is not None: - request.constraint = constraint - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_org_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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(( - ("scope", request.scope), - )), - ) - - # 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.AnalyzeOrgPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_org_policy_governed_containers(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager: - r"""Analyzes organization policies governed containers - (projects, folders or organization) under a scope. - - .. 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 asset_v1 - - async def sample_analyze_org_policy_governed_containers(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_containers(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest, dict]]): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - scope (:class:`str`): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. - The output containers will also be limited to the ones - governed by those in-scope organization policies. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - constraint (:class:`str`): - Required. The name of the constraint - to analyze governed containers for. The - analysis only contains organization - policies for the provided constraint. - - This corresponds to the ``constraint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The expression to filter the governed containers in - result. The only supported field is ``parent``, and the - only supported operator is ``=``. - - Example: - parent="//cloudresourcemanager.googleapis.com/folders/001" - will return all containers under "folders/001". - - This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - - 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([scope, constraint, filter]) - 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 = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if constraint is not None: - request.constraint = constraint - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_org_policy_governed_containers, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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(( - ("scope", request.scope), - )), - ) - - # 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.AnalyzeOrgPolicyGovernedContainersAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def analyze_org_policy_governed_assets(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager: - r"""Analyzes organization policies governed assets (Google Cloud - resources or policies) under a scope. This RPC supports custom - constraints and the following 10 canned constraints: - - - storage.uniformBucketLevelAccess - - iam.disableServiceAccountKeyCreation - - iam.allowedPolicyMemberDomains - - compute.vmExternalIpAccess - - appengine.enforceServiceAccountActAsCheck - - gcp.resourceLocations - - compute.trustedImageProjects - - compute.skipDefaultNetworkCreation - - compute.requireOsLogin - - compute.disableNestedVirtualization - - This RPC only returns either resources of types supported by - `searchable asset - types `__, - or IAM policies. - - .. 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 asset_v1 - - async def sample_analyze_org_policy_governed_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest, dict]]): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - scope (:class:`str`): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. - The output assets will also be limited to the ones - governed by those in-scope organization policies. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - constraint (:class:`str`): - Required. The name of the constraint - to analyze governed assets for. The - analysis only contains analyzed - organization policies for the provided - constraint. - - This corresponds to the ``constraint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (:class:`str`): - The expression to filter the governed assets in result. - The only supported fields for governed resources are - ``governed_resource.project`` and - ``governed_resource.folders``. The only supported fields - for governed iam policies are - ``governed_iam_policy.project`` and - ``governed_iam_policy.folders``. The only supported - operator is ``=``. - - Example 1: governed_resource.project="projects/12345678" - filter will return all governed resources under - projects/12345678 including the project ifself, if - applicable. - - Example 2: - governed_iam_policy.folders="folders/12345678" filter - will return all governed iam policies under - folders/12345678, if applicable. - - This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - - 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([scope, constraint, filter]) - 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if constraint is not None: - request.constraint = constraint - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.analyze_org_policy_governed_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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(( - ("scope", request.scope), - )), - ) - - # 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.AnalyzeOrgPolicyGovernedAssetsAsyncPager( - method=rpc, - request=request, - response=response, - 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 __aenter__(self) -> "AssetServiceAsyncClient": - 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__ = ( - "AssetServiceAsyncClient", -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py deleted file mode 100644 index 7a9d4c08..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py +++ /dev/null @@ -1,3329 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.asset_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.asset_v1.services.asset_service import pagers -from google.cloud.asset_v1.types import asset_service -from google.cloud.asset_v1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .transports.rest import AssetServiceRestTransport - - -class AssetServiceClientMeta(type): - """Metaclass for the AssetService 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[AssetServiceTransport]] - _transport_registry["grpc"] = AssetServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AssetServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AssetServiceTransport]: - """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 AssetServiceClient(metaclass=AssetServiceClientMeta): - """Asset service definition.""" - - @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 = "cloudasset.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: - AssetServiceClient: 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: - AssetServiceClient: 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) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def access_level_path(access_policy: str,access_level: str,) -> str: - """Returns a fully-qualified access_level string.""" - return "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) - - @staticmethod - def parse_access_level_path(path: str) -> Dict[str,str]: - """Parses a access_level path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def access_policy_path(access_policy: str,) -> str: - """Returns a fully-qualified access_policy string.""" - return "accessPolicies/{access_policy}".format(access_policy=access_policy, ) - - @staticmethod - def parse_access_policy_path(path: str) -> Dict[str,str]: - """Parses a access_policy path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def asset_path() -> str: - """Returns a fully-qualified asset string.""" - return "*".format() - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^.*$", path) - return m.groupdict() if m else {} - - @staticmethod - def feed_path(project: str,feed: str,) -> str: - """Returns a fully-qualified feed string.""" - return "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) - - @staticmethod - def parse_feed_path(path: str) -> Dict[str,str]: - """Parses a feed path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def inventory_path(project: str,location: str,instance: str,) -> str: - """Returns a fully-qualified inventory string.""" - return "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) - - @staticmethod - def parse_inventory_path(path: str) -> Dict[str,str]: - """Parses a inventory path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/inventory$", path) - return m.groupdict() if m else {} - - @staticmethod - def saved_query_path(project: str,saved_query: str,) -> str: - """Returns a fully-qualified saved_query string.""" - return "projects/{project}/savedQueries/{saved_query}".format(project=project, saved_query=saved_query, ) - - @staticmethod - def parse_saved_query_path(path: str) -> Dict[str,str]: - """Parses a saved_query path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/savedQueries/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_perimeter_path(access_policy: str,service_perimeter: str,) -> str: - """Returns a fully-qualified service_perimeter string.""" - return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) - - @staticmethod - def parse_service_perimeter_path(path: str) -> Dict[str,str]: - """Parses a service_perimeter path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/servicePerimeters/(?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, AssetServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): - # transport is a AssetServiceTransport 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 export_assets(self, - request: Optional[Union[asset_service.ExportAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports assets with time and resource types to a given Cloud - Storage location/BigQuery table. For Cloud Storage location - destinations, the output format is newline-delimited JSON. Each - line represents a - [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in - the JSON format; for BigQuery table destinations, the output - table stores the fields in asset Protobuf as columns. This API - implements the - [google.longrunning.Operation][google.longrunning.Operation] - API, which allows you to keep track of the export. We recommend - intervals of at least 2 seconds with exponential retry to poll - the export operation result. For regular-size resource parent, - the export operation usually finishes within 5 minutes. - - .. 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 asset_v1 - - def sample_export_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - output_config = asset_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.ExportAssetsRequest( - parent="parent_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_assets(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.ExportAssetsRequest, dict]): - The request object. Export asset request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.ExportAssetsResponse` The export asset response. This message is returned by the - [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] - method in the returned - [google.longrunning.Operation.response][google.longrunning.Operation.response] - field. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.ExportAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ExportAssetsRequest): - request = asset_service.ExportAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_assets] - - # 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, - asset_service.ExportAssetsResponse, - metadata_type=asset_service.ExportAssetsRequest, - ) - - # Done; return the response. - return response - - def list_assets(self, - request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - .. 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 asset_v1 - - def sample_list_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.ListAssetsRequest, dict]): - The request object. ListAssets request. - parent (str): - Required. Name of the organization, folder, or project - the assets belong to. Format: - "organizations/[organization-number]" (such as - "organizations/123"), "projects/[project-id]" (such as - "projects/my-project-id"), "projects/[project-number]" - (such as "projects/12345"), or "folders/[folder-number]" - (such as "folders/12345"). - - 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.asset_v1.services.asset_service.pagers.ListAssetsPager: - ListAssets response. - - 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 asset_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ListAssetsRequest): - request = asset_service.ListAssetsRequest(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_assets] - - # 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.ListAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def batch_get_assets_history(self, - request: Optional[Union[asset_service.BatchGetAssetsHistoryRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: - r"""Batch gets the update history of assets that overlap a time - window. For IAM_POLICY content, this API outputs history when - the asset and its attached IAM POLICY both exist. This can - create gaps in the output history. Otherwise, this API outputs - history with asset in both non-delete or deleted status. If a - specified asset does not exist, this API returns an - INVALID_ARGUMENT error. - - .. 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 asset_v1 - - def sample_batch_get_assets_history(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetAssetsHistoryRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_get_assets_history(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest, dict]): - The request object. Batch get assets history request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.BatchGetAssetsHistoryResponse: - Batch get assets history response. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.BatchGetAssetsHistoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.BatchGetAssetsHistoryRequest): - request = asset_service.BatchGetAssetsHistoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_get_assets_history] - - # 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 create_feed(self, - request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - .. 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 asset_v1 - - def sample_create_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = client.create_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.CreateFeedRequest, dict]): - The request object. Create asset feed request. - parent (str): - Required. The name of the - project/folder/organization where this - feed should be created in. It can only - be an organization number (such as - "organizations/123"), a folder number - (such as "folders/123"), a project ID - (such as "projects/my-project-id"), or a - project number (such as - "projects/12345"). - - 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.asset_v1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - # 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 asset_service.CreateFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.CreateFeedRequest): - request = asset_service.CreateFeedRequest(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.create_feed] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_feed(self, - request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - .. 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 asset_v1 - - def sample_get_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = client.get_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.GetFeedRequest, dict]): - The request object. Get asset feed request. - name (str): - Required. The name of the Feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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.asset_v1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - # 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 asset_service.GetFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.GetFeedRequest): - request = asset_service.GetFeedRequest(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_feed] - - # 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_feeds(self, - request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - .. 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 asset_v1 - - def sample_list_feeds(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_feeds(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.ListFeedsRequest, dict]): - The request object. List asset feeds request. - parent (str): - Required. The parent - project/folder/organization whose feeds - are to be listed. It can only be using - project/folder/organization number (such - as "folders/12345")", or a project ID - (such as "projects/my-project-id"). - - 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.asset_v1.types.ListFeedsResponse: - - """ - # 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 asset_service.ListFeedsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ListFeedsRequest): - request = asset_service.ListFeedsRequest(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_feeds] - - # 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_feed(self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - .. 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 asset_v1 - - def sample_update_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = client.update_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.UpdateFeedRequest, dict]): - The request object. Update asset feed request. - feed (google.cloud.asset_v1.types.Feed): - Required. The new values of feed details. It must match - an existing feed and the field ``name`` must be in the - format of: projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - - This corresponds to the ``feed`` 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.asset_v1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - # 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([feed]) - 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 asset_service.UpdateFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.UpdateFeedRequest): - request = asset_service.UpdateFeedRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if feed is not None: - request.feed = feed - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_feed] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("feed.name", request.feed.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_feed(self, - request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. - - .. 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 asset_v1 - - def sample_delete_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - client.delete_feed(request=request) - - Args: - request (Union[google.cloud.asset_v1.types.DeleteFeedRequest, dict]): - The request object. - name (str): - Required. The name of the feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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 asset_service.DeleteFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.DeleteFeedRequest): - request = asset_service.DeleteFeedRequest(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_feed] - - # 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 search_all_resources(self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesPager: - r"""Searches all Google Cloud resources within the specified scope, - such as a project, folder, or organization. The caller must be - granted the ``cloudasset.assets.searchAllResources`` permission - on the desired scope, otherwise the request will be rejected. - - .. 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 asset_v1 - - def sample_search_all_resources(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.SearchAllResourcesRequest, dict]): - The request object. Search all resources request. - scope (str): - Required. A scope can be a project, a folder, or an - organization. The search is limited to the resources - within the ``scope``. The caller must be granted the - ```cloudasset.assets.searchAllResources`` `__ - permission on the desired scope. - - The allowed values are: - - - projects/{PROJECT_ID} (e.g., "projects/foo-bar") - - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") - - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (str): - Optional. The query statement. See `how to construct a - query `__ - for more information. If not specified or empty, it will - search all the resources within the specified ``scope``. - - Examples: - - - ``name:Important`` to find Google Cloud resources - whose name contains ``Important`` as a word. - - ``name=Important`` to find the Google Cloud resource - whose name is exactly ``Important``. - - ``displayName:Impor*`` to find Google Cloud resources - whose display name contains ``Impor`` as a prefix of - any word in the field. - - ``location:us-west*`` to find Google Cloud resources - whose location contains both ``us`` and ``west`` as - prefixes. - - ``labels:prod`` to find Google Cloud resources whose - labels contain ``prod`` as a key or value. - - ``labels.env:prod`` to find Google Cloud resources - that have a label ``env`` and its value is ``prod``. - - ``labels.env:*`` to find Google Cloud resources that - have a label ``env``. - - ``tagKeys:env`` to find Google Cloud resources that - have directly attached tags where the - ```TagKey`` `__ - .\ ``namespacedName`` contains ``env``. - - ``tagValues:prod*`` to find Google Cloud resources - that have directly attached tags where the - ```TagValue`` `__ - .\ ``namespacedName`` contains a word prefixed by - ``prod``. - - ``tagValueIds=tagValues/123`` to find Google Cloud - resources that have directly attached tags where the - ```TagValue`` `__ - .\ ``name`` is exactly ``tagValues/123``. - - ``effectiveTagKeys:env`` to find Google Cloud - resources that have directly attached or inherited - tags where the - ```TagKey`` `__ - .\ ``namespacedName`` contains ``env``. - - ``effectiveTagValues:prod*`` to find Google Cloud - resources that have directly attached or inherited - tags where the - ```TagValue`` `__ - .\ ``namespacedName`` contains a word prefixed by - ``prod``. - - ``effectiveTagValueIds=tagValues/123`` to find Google - Cloud resources that have directly attached or - inherited tags where the - ```TagValue`` `__ - .\ ``name`` is exactly ``tagValues/123``. - - ``kmsKey:key`` to find Google Cloud resources - encrypted with a customer-managed encryption key - whose name contains ``key`` as a word. This field is - deprecated. Please use the ``kmsKeys`` field to - retrieve Cloud KMS key information. - - ``kmsKeys:key`` to find Google Cloud resources - encrypted with customer-managed encryption keys whose - name contains the word ``key``. - - ``relationships:instance-group-1`` to find Google - Cloud resources that have relationships with - ``instance-group-1`` in the related resource name. - - ``relationships:INSTANCE_TO_INSTANCEGROUP`` to find - Compute Engine instances that have relationships of - type ``INSTANCE_TO_INSTANCEGROUP``. - - ``relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1`` - to find Compute Engine instances that have - relationships with ``instance-group-1`` in the - Compute Engine instance group resource name, for - relationship type ``INSTANCE_TO_INSTANCEGROUP``. - - ``state:ACTIVE`` to find Google Cloud resources whose - state contains ``ACTIVE`` as a word. - - ``NOT state:ACTIVE`` to find Google Cloud resources - whose state doesn't contain ``ACTIVE`` as a word. - - ``createTime<1609459200`` to find Google Cloud - resources that were created before - ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the - epoch timestamp of ``2021-01-01 00:00:00 UTC`` in - seconds. - - ``updateTime>1609459200`` to find Google Cloud - resources that were updated after - ``2021-01-01 00:00:00 UTC``. ``1609459200`` is the - epoch timestamp of ``2021-01-01 00:00:00 UTC`` in - seconds. - - ``Important`` to find Google Cloud resources that - contain ``Important`` as a word in any of the - searchable fields. - - ``Impor*`` to find Google Cloud resources that - contain ``Impor`` as a prefix of any word in any of - the searchable fields. - - ``Important location:(us-west1 OR global)`` to find - Google Cloud resources that contain ``Important`` as - a word in any of the searchable fields and are also - located in the ``us-west1`` region or the ``global`` - location. - - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - asset_types (MutableSequence[str]): - Optional. A list of asset types that this request - searches for. If empty, it will search all the - `searchable asset - types `__. - - Regular expressions are also supported. For example: - - - "compute.googleapis.com.*" snapshots resources whose - asset type starts with "compute.googleapis.com". - - ".*Instance" snapshots resources whose asset type - ends with "Instance". - - ".*Instance.*" snapshots resources whose asset type - contains "Instance". - - See `RE2 `__ - for all supported regular expression syntax. If the - regular expression does not match any supported asset - type, an INVALID_ARGUMENT error will be returned. - - This corresponds to the ``asset_types`` 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.asset_v1.services.asset_service.pagers.SearchAllResourcesPager: - Search all resources response. - - 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([scope, query, asset_types]) - 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 asset_service.SearchAllResourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.SearchAllResourcesRequest): - request = asset_service.SearchAllResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - if asset_types is not None: - request.asset_types = asset_types - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_all_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllResourcesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_all_iam_policies(self, - request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllIamPoliciesPager: - r"""Searches all IAM policies within the specified scope, such as a - project, folder, or organization. The caller must be granted the - ``cloudasset.assets.searchAllIamPolicies`` permission on the - desired scope, otherwise the request will be rejected. - - .. 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 asset_v1 - - def sample_search_all_iam_policies(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.SearchAllIamPoliciesRequest, dict]): - The request object. Search all IAM policies request. - scope (str): - Required. A scope can be a project, a folder, or an - organization. The search is limited to the IAM policies - within the ``scope``. The caller must be granted the - ```cloudasset.assets.searchAllIamPolicies`` `__ - permission on the desired scope. - - The allowed values are: - - - projects/{PROJECT_ID} (e.g., "projects/foo-bar") - - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") - - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (str): - Optional. The query statement. See `how to construct a - query `__ - for more information. If not specified or empty, it will - search all the IAM policies within the specified - ``scope``. Note that the query string is compared - against each IAM policy binding, including its - principals, roles, and IAM conditions. The returned IAM - policies will only contain the bindings that match your - query. To learn more about the IAM policy structure, see - the `IAM policy - documentation `__. - - Examples: - - - ``policy:amy@gmail.com`` to find IAM policy bindings - that specify user "amy@gmail.com". - - ``policy:roles/compute.admin`` to find IAM policy - bindings that specify the Compute Admin role. - - ``policy:comp*`` to find IAM policy bindings that - contain "comp" as a prefix of any word in the - binding. - - ``policy.role.permissions:storage.buckets.update`` to - find IAM policy bindings that specify a role - containing "storage.buckets.update" permission. Note - that if callers don't have ``iam.roles.get`` access - to a role's included permissions, policy bindings - that specify this role will be dropped from the - search results. - - ``policy.role.permissions:upd*`` to find IAM policy - bindings that specify a role containing "upd" as a - prefix of any word in the role permission. Note that - if callers don't have ``iam.roles.get`` access to a - role's included permissions, policy bindings that - specify this role will be dropped from the search - results. - - ``resource:organizations/123456`` to find IAM policy - bindings that are set on "organizations/123456". - - ``resource=//cloudresourcemanager.googleapis.com/projects/myproject`` - to find IAM policy bindings that are set on the - project named "myproject". - - ``Important`` to find IAM policy bindings that - contain "Important" as a word in any of the - searchable fields (except for the included - permissions). - - ``resource:(instance1 OR instance2) policy:amy`` to - find IAM policy bindings that are set on resources - "instance1" or "instance2" and also specify user - "amy". - - ``roles:roles/compute.admin`` to find IAM policy - bindings that specify the Compute Admin role. - - ``memberTypes:user`` to find IAM policy bindings that - contain the principal type "user". - - This corresponds to the ``query`` 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.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesPager: - Search all IAM policies response. - - 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([scope, query]) - 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 asset_service.SearchAllIamPoliciesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): - request = asset_service.SearchAllIamPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_all_iam_policies] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllIamPoliciesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_iam_policy(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: - r"""Analyzes IAM policies to answer which identities have - what accesses on which resources. - - .. 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 asset_v1 - - def sample_analyze_iam_policy(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - request = asset_v1.AnalyzeIamPolicyRequest( - analysis_query=analysis_query, - ) - - # Make the request - response = client.analyze_iam_policy(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.AnalyzeIamPolicyRequest, dict]): - The request object. A request message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.AnalyzeIamPolicyResponse: - A response message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.AnalyzeIamPolicyRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.AnalyzeIamPolicyRequest): - request = asset_service.AnalyzeIamPolicyRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_iam_policy_longrunning(self, - request: Optional[Union[asset_service.AnalyzeIamPolicyLongrunningRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Analyzes IAM policies asynchronously to answer which identities - have what accesses on which resources, and writes the analysis - results to a Google Cloud Storage or a BigQuery destination. For - Cloud Storage destination, the output format is the JSON format - that represents a - [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. - This method implements the - [google.longrunning.Operation][google.longrunning.Operation], - which allows you to track the operation status. We recommend - intervals of at least 2 seconds with exponential backoff retry - to poll the operation result. The metadata contains the metadata - for the long-running operation. - - .. 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 asset_v1 - - def sample_analyze_iam_policy_longrunning(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - output_config = asset_v1.IamPolicyAnalysisOutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.AnalyzeIamPolicyLongrunningRequest( - analysis_query=analysis_query, - output_config=output_config, - ) - - # Make the request - operation = client.analyze_iam_policy_longrunning(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest, dict]): - The request object. A request message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.AnalyzeIamPolicyLongrunningResponse` A response message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.AnalyzeIamPolicyLongrunningRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.AnalyzeIamPolicyLongrunningRequest): - request = asset_service.AnalyzeIamPolicyLongrunningRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_iam_policy_longrunning] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.scope", request.analysis_query.scope), - )), - ) - - # 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, - asset_service.AnalyzeIamPolicyLongrunningResponse, - metadata_type=asset_service.AnalyzeIamPolicyLongrunningMetadata, - ) - - # Done; return the response. - return response - - def analyze_move(self, - request: Optional[Union[asset_service.AnalyzeMoveRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeMoveResponse: - r"""Analyze moving a resource to a specified destination - without kicking off the actual move. The analysis is - best effort depending on the user's permissions of - viewing different hierarchical policies and - configurations. The policies and configuration are - subject to change before the actual resource migration - takes place. - - .. 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 asset_v1 - - def sample_analyze_move(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeMoveRequest( - resource="resource_value", - destination_parent="destination_parent_value", - ) - - # Make the request - response = client.analyze_move(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.AnalyzeMoveRequest, dict]): - The request object. The request message for performing - resource move analysis. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.AnalyzeMoveResponse: - The response message for resource - move analysis. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.AnalyzeMoveRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.AnalyzeMoveRequest): - request = asset_service.AnalyzeMoveRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_move] - - # 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 query_assets(self, - request: Optional[Union[asset_service.QueryAssetsRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.QueryAssetsResponse: - r"""Issue a job that queries assets using a SQL statement compatible - with `BigQuery - SQL `__. - - If the query execution finishes within timeout and there's no - pagination, the full query results will be returned in the - ``QueryAssetsResponse``. - - Otherwise, full query results can be obtained by issuing extra - requests with the ``job_reference`` from the a previous - ``QueryAssets`` call. - - Note, the query result has approximately 10 GB limitation - enforced by - `BigQuery `__. - Queries return larger results will result in errors. - - .. 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 asset_v1 - - def sample_query_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.QueryAssetsRequest( - statement="statement_value", - parent="parent_value", - ) - - # Make the request - response = client.query_assets(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.QueryAssetsRequest, dict]): - The request object. QueryAssets request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.QueryAssetsResponse: - QueryAssets response. - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.QueryAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.QueryAssetsRequest): - request = asset_service.QueryAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.query_assets] - - # 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 create_saved_query(self, - request: Optional[Union[asset_service.CreateSavedQueryRequest, dict]] = None, - *, - parent: Optional[str] = None, - saved_query: Optional[asset_service.SavedQuery] = None, - saved_query_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.SavedQuery: - r"""Creates a saved query in a parent - project/folder/organization. - - .. 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 asset_v1 - - def sample_create_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.CreateSavedQueryRequest( - parent="parent_value", - saved_query_id="saved_query_id_value", - ) - - # Make the request - response = client.create_saved_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.CreateSavedQueryRequest, dict]): - The request object. Request to create a saved query. - parent (str): - Required. The name of the project/folder/organization - where this saved_query should be created in. It can only - be an organization number (such as "organizations/123"), - a folder number (such as "folders/123"), a project ID - (such as "projects/my-project-id"), or a project number - (such as "projects/12345"). - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - saved_query (google.cloud.asset_v1.types.SavedQuery): - Required. The saved_query details. The ``name`` field - must be empty as it will be generated based on the - parent and saved_query_id. - - This corresponds to the ``saved_query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - saved_query_id (str): - Required. The ID to use for the saved query, which must - be unique in the specified parent. It will become the - final component of the saved query's resource name. - - This value should be 4-63 characters, and valid - characters are ``[a-z][0-9]-``. - - Notice that this field is required in the saved query - creation, and the ``name`` field of the ``saved_query`` - will be ignored. - - This corresponds to the ``saved_query_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.asset_v1.types.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - # 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, saved_query, saved_query_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 asset_service.CreateSavedQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.CreateSavedQueryRequest): - request = asset_service.CreateSavedQueryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if saved_query is not None: - request.saved_query = saved_query - if saved_query_id is not None: - request.saved_query_id = saved_query_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_saved_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_saved_query(self, - request: Optional[Union[asset_service.GetSavedQueryRequest, 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]] = (), - ) -> asset_service.SavedQuery: - r"""Gets details about a saved query. - - .. 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 asset_v1 - - def sample_get_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.GetSavedQueryRequest( - name="name_value", - ) - - # Make the request - response = client.get_saved_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.GetSavedQueryRequest, dict]): - The request object. Request to get a saved query. - name (str): - Required. The name of the saved query and it must be in - the format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - 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.asset_v1.types.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - # 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 asset_service.GetSavedQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.GetSavedQueryRequest): - request = asset_service.GetSavedQueryRequest(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_saved_query] - - # 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_saved_queries(self, - request: Optional[Union[asset_service.ListSavedQueriesRequest, 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.ListSavedQueriesPager: - r"""Lists all saved queries in a parent - project/folder/organization. - - .. 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 asset_v1 - - def sample_list_saved_queries(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.ListSavedQueriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_saved_queries(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.ListSavedQueriesRequest, dict]): - The request object. Request to list saved queries. - parent (str): - Required. The parent - project/folder/organization whose - savedQueries are to be listed. It can - only be using - project/folder/organization number (such - as "folders/12345")", or a project ID - (such as "projects/my-project-id"). - - 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.asset_v1.services.asset_service.pagers.ListSavedQueriesPager: - Response of listing saved queries. - - 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 asset_service.ListSavedQueriesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ListSavedQueriesRequest): - request = asset_service.ListSavedQueriesRequest(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_saved_queries] - - # 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.ListSavedQueriesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_saved_query(self, - request: Optional[Union[asset_service.UpdateSavedQueryRequest, dict]] = None, - *, - saved_query: Optional[asset_service.SavedQuery] = 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]] = (), - ) -> asset_service.SavedQuery: - r"""Updates a saved query. - - .. 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 asset_v1 - - def sample_update_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.UpdateSavedQueryRequest( - ) - - # Make the request - response = client.update_saved_query(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.UpdateSavedQueryRequest, dict]): - The request object. Request to update a saved query. - saved_query (google.cloud.asset_v1.types.SavedQuery): - Required. The saved query to update. - - The saved query's ``name`` field is used to identify the - one to update, which has format as below: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - This corresponds to the ``saved_query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to - update. - - 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.asset_v1.types.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - # 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([saved_query, 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 asset_service.UpdateSavedQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.UpdateSavedQueryRequest): - request = asset_service.UpdateSavedQueryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if saved_query is not None: - request.saved_query = saved_query - 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_saved_query] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("saved_query.name", request.saved_query.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_saved_query(self, - request: Optional[Union[asset_service.DeleteSavedQueryRequest, 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"""Deletes a saved query. - - .. 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 asset_v1 - - def sample_delete_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.DeleteSavedQueryRequest( - name="name_value", - ) - - # Make the request - client.delete_saved_query(request=request) - - Args: - request (Union[google.cloud.asset_v1.types.DeleteSavedQueryRequest, dict]): - The request object. Request to delete a saved query. - name (str): - Required. The name of the saved query to delete. It must - be in the format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - 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 asset_service.DeleteSavedQueryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.DeleteSavedQueryRequest): - request = asset_service.DeleteSavedQueryRequest(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_saved_query] - - # 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 batch_get_effective_iam_policies(self, - request: Optional[Union[asset_service.BatchGetEffectiveIamPoliciesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: - r"""Gets effective IAM policies for a batch of resources. - - .. 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 asset_v1 - - def sample_batch_get_effective_iam_policies(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetEffectiveIamPoliciesRequest( - scope="scope_value", - names=['names_value1', 'names_value2'], - ) - - # Make the request - response = client.batch_get_effective_iam_policies(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest, dict]): - The request object. A request message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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.asset_v1.types.BatchGetEffectiveIamPoliciesResponse: - A response message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - - """ - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.BatchGetEffectiveIamPoliciesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.BatchGetEffectiveIamPoliciesRequest): - request = asset_service.BatchGetEffectiveIamPoliciesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_get_effective_iam_policies] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_org_policies(self, - request: Optional[Union[asset_service.AnalyzeOrgPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.AnalyzeOrgPoliciesPager: - r"""Analyzes organization policies under a scope. - - .. 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 asset_v1 - - def sample_analyze_org_policies(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPoliciesRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest, dict]): - The request object. A request message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - scope (str): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - constraint (str): - Required. The name of the constraint - to analyze organization policies for. - The response only contains analyzed - organization policies for the provided - constraint. - - This corresponds to the ``constraint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The expression to filter - [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. - The only supported field is - ``consolidated_policy.attached_resource``, and the only - supported operator is ``=``. - - Example: - consolidated_policy.attached_resource="//cloudresourcemanager.googleapis.com/folders/001" - will return the org policy results of"folders/001". - - This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesPager: - The response message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - - 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([scope, constraint, filter]) - 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 asset_service.AnalyzeOrgPoliciesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.AnalyzeOrgPoliciesRequest): - request = asset_service.AnalyzeOrgPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if constraint is not None: - request.constraint = constraint - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_org_policies] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # 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.AnalyzeOrgPoliciesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_org_policy_governed_containers(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedContainersPager: - r"""Analyzes organization policies governed containers - (projects, folders or organization) under a scope. - - .. 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 asset_v1 - - def sample_analyze_org_policy_governed_containers(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_containers(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest, dict]): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - scope (str): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. - The output containers will also be limited to the ones - governed by those in-scope organization policies. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - constraint (str): - Required. The name of the constraint - to analyze governed containers for. The - analysis only contains organization - policies for the provided constraint. - - This corresponds to the ``constraint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The expression to filter the governed containers in - result. The only supported field is ``parent``, and the - only supported operator is ``=``. - - Example: - parent="//cloudresourcemanager.googleapis.com/folders/001" - will return all containers under "folders/001". - - This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersPager: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - - 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([scope, constraint, filter]) - 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 asset_service.AnalyzeOrgPolicyGovernedContainersRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedContainersRequest): - request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if constraint is not None: - request.constraint = constraint - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_containers] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # 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.AnalyzeOrgPolicyGovernedContainersPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def analyze_org_policy_governed_assets(self, - request: Optional[Union[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, dict]] = None, - *, - scope: Optional[str] = None, - constraint: Optional[str] = None, - filter: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.AnalyzeOrgPolicyGovernedAssetsPager: - r"""Analyzes organization policies governed assets (Google Cloud - resources or policies) under a scope. This RPC supports custom - constraints and the following 10 canned constraints: - - - storage.uniformBucketLevelAccess - - iam.disableServiceAccountKeyCreation - - iam.allowedPolicyMemberDomains - - compute.vmExternalIpAccess - - appengine.enforceServiceAccountActAsCheck - - gcp.resourceLocations - - compute.trustedImageProjects - - compute.skipDefaultNetworkCreation - - compute.requireOsLogin - - compute.disableNestedVirtualization - - This RPC only returns either resources of types supported by - `searchable asset - types `__, - or IAM policies. - - .. 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 asset_v1 - - def sample_analyze_org_policy_governed_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest, dict]): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - scope (str): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. - The output assets will also be limited to the ones - governed by those in-scope organization policies. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - constraint (str): - Required. The name of the constraint - to analyze governed assets for. The - analysis only contains analyzed - organization policies for the provided - constraint. - - This corresponds to the ``constraint`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - filter (str): - The expression to filter the governed assets in result. - The only supported fields for governed resources are - ``governed_resource.project`` and - ``governed_resource.folders``. The only supported fields - for governed iam policies are - ``governed_iam_policy.project`` and - ``governed_iam_policy.folders``. The only supported - operator is ``=``. - - Example 1: governed_resource.project="projects/12345678" - filter will return all governed resources under - projects/12345678 including the project ifself, if - applicable. - - Example 2: - governed_iam_policy.folders="folders/12345678" filter - will return all governed iam policies under - folders/12345678, if applicable. - - This corresponds to the ``filter`` 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.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsPager: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - - 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([scope, constraint, filter]) - 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 asset_service.AnalyzeOrgPolicyGovernedAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): - request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if constraint is not None: - request.constraint = constraint - if filter is not None: - request.filter = filter - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.analyze_org_policy_governed_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # 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.AnalyzeOrgPolicyGovernedAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AssetServiceClient": - 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 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 - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AssetServiceClient", -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py deleted file mode 100644 index 8f71ac0d..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py +++ /dev/null @@ -1,866 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.asset_v1.types import asset_service -from google.cloud.asset_v1.types import assets - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``assets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``assets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.ListAssetsResponse` - 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[..., asset_service.ListAssetsResponse], - request: asset_service.ListAssetsRequest, - response: asset_service.ListAssetsResponse, - *, - 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.asset_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.asset_v1.types.ListAssetsResponse): - 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 = asset_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.ListAssetsResponse]: - 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[assets.Asset]: - for page in self.pages: - yield from page.assets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``assets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``assets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.ListAssetsResponse` - 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[asset_service.ListAssetsResponse]], - request: asset_service.ListAssetsRequest, - response: asset_service.ListAssetsResponse, - *, - 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.asset_v1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.asset_v1.types.ListAssetsResponse): - 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 = asset_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.ListAssetsResponse]: - 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[assets.Asset]: - async def async_generator(): - async for page in self.pages: - for response in page.assets: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAllResourcesPager: - """A pager for iterating through ``search_all_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchAllResources`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` - 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[..., asset_service.SearchAllResourcesResponse], - request: asset_service.SearchAllResourcesRequest, - response: asset_service.SearchAllResourcesResponse, - *, - 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.asset_v1.types.SearchAllResourcesRequest): - The initial request object. - response (google.cloud.asset_v1.types.SearchAllResourcesResponse): - 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 = asset_service.SearchAllResourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.SearchAllResourcesResponse]: - 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[assets.ResourceSearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAllResourcesAsyncPager: - """A pager for iterating through ``search_all_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchAllResources`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.SearchAllResourcesResponse` - 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[asset_service.SearchAllResourcesResponse]], - request: asset_service.SearchAllResourcesRequest, - response: asset_service.SearchAllResourcesResponse, - *, - 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.asset_v1.types.SearchAllResourcesRequest): - The initial request object. - response (google.cloud.asset_v1.types.SearchAllResourcesResponse): - 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 = asset_service.SearchAllResourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.SearchAllResourcesResponse]: - 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[assets.ResourceSearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAllIamPoliciesPager: - """A pager for iterating through ``search_all_iam_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchAllIamPolicies`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` - 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[..., asset_service.SearchAllIamPoliciesResponse], - request: asset_service.SearchAllIamPoliciesRequest, - response: asset_service.SearchAllIamPoliciesResponse, - *, - 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.asset_v1.types.SearchAllIamPoliciesRequest): - The initial request object. - response (google.cloud.asset_v1.types.SearchAllIamPoliciesResponse): - 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 = asset_service.SearchAllIamPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.SearchAllIamPoliciesResponse]: - 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[assets.IamPolicySearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAllIamPoliciesAsyncPager: - """A pager for iterating through ``search_all_iam_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchAllIamPolicies`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.SearchAllIamPoliciesResponse` - 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[asset_service.SearchAllIamPoliciesResponse]], - request: asset_service.SearchAllIamPoliciesRequest, - response: asset_service.SearchAllIamPoliciesResponse, - *, - 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.asset_v1.types.SearchAllIamPoliciesRequest): - The initial request object. - response (google.cloud.asset_v1.types.SearchAllIamPoliciesResponse): - 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 = asset_service.SearchAllIamPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.SearchAllIamPoliciesResponse]: - 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[assets.IamPolicySearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSavedQueriesPager: - """A pager for iterating through ``list_saved_queries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``saved_queries`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSavedQueries`` requests and continue to iterate - through the ``saved_queries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` - 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[..., asset_service.ListSavedQueriesResponse], - request: asset_service.ListSavedQueriesRequest, - response: asset_service.ListSavedQueriesResponse, - *, - 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.asset_v1.types.ListSavedQueriesRequest): - The initial request object. - response (google.cloud.asset_v1.types.ListSavedQueriesResponse): - 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 = asset_service.ListSavedQueriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.ListSavedQueriesResponse]: - 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[asset_service.SavedQuery]: - for page in self.pages: - yield from page.saved_queries - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListSavedQueriesAsyncPager: - """A pager for iterating through ``list_saved_queries`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``saved_queries`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSavedQueries`` requests and continue to iterate - through the ``saved_queries`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.ListSavedQueriesResponse` - 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[asset_service.ListSavedQueriesResponse]], - request: asset_service.ListSavedQueriesRequest, - response: asset_service.ListSavedQueriesResponse, - *, - 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.asset_v1.types.ListSavedQueriesRequest): - The initial request object. - response (google.cloud.asset_v1.types.ListSavedQueriesResponse): - 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 = asset_service.ListSavedQueriesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.ListSavedQueriesResponse]: - 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[asset_service.SavedQuery]: - async def async_generator(): - async for page in self.pages: - for response in page.saved_queries: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class AnalyzeOrgPoliciesPager: - """A pager for iterating through ``analyze_org_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``org_policy_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``AnalyzeOrgPolicies`` requests and continue to iterate - through the ``org_policy_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` - 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[..., asset_service.AnalyzeOrgPoliciesResponse], - request: asset_service.AnalyzeOrgPoliciesRequest, - response: asset_service.AnalyzeOrgPoliciesResponse, - *, - 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.asset_v1.types.AnalyzeOrgPoliciesRequest): - The initial request object. - response (google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse): - 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 = asset_service.AnalyzeOrgPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.AnalyzeOrgPoliciesResponse]: - 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[asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult]: - for page in self.pages: - yield from page.org_policy_results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class AnalyzeOrgPoliciesAsyncPager: - """A pager for iterating through ``analyze_org_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``org_policy_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``AnalyzeOrgPolicies`` requests and continue to iterate - through the ``org_policy_results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse` - 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[asset_service.AnalyzeOrgPoliciesResponse]], - request: asset_service.AnalyzeOrgPoliciesRequest, - response: asset_service.AnalyzeOrgPoliciesResponse, - *, - 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.asset_v1.types.AnalyzeOrgPoliciesRequest): - The initial request object. - response (google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse): - 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 = asset_service.AnalyzeOrgPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.AnalyzeOrgPoliciesResponse]: - 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[asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult]: - async def async_generator(): - async for page in self.pages: - for response in page.org_policy_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class AnalyzeOrgPolicyGovernedContainersPager: - """A pager for iterating through ``analyze_org_policy_governed_containers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` object, and - provides an ``__iter__`` method to iterate through its - ``governed_containers`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``AnalyzeOrgPolicyGovernedContainers`` requests and continue to iterate - through the ``governed_containers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` - 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[..., asset_service.AnalyzeOrgPolicyGovernedContainersResponse], - request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, - response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse, - *, - 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.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest): - The initial request object. - response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse): - 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 = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: - 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[asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer]: - for page in self.pages: - yield from page.governed_containers - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class AnalyzeOrgPolicyGovernedContainersAsyncPager: - """A pager for iterating through ``analyze_org_policy_governed_containers`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``governed_containers`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``AnalyzeOrgPolicyGovernedContainers`` requests and continue to iterate - through the ``governed_containers`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse` - 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[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]], - request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, - response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse, - *, - 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.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest): - The initial request object. - response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse): - 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 = asset_service.AnalyzeOrgPolicyGovernedContainersRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: - 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[asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer]: - async def async_generator(): - async for page in self.pages: - for response in page.governed_containers: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class AnalyzeOrgPolicyGovernedAssetsPager: - """A pager for iterating through ``analyze_org_policy_governed_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``governed_assets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``AnalyzeOrgPolicyGovernedAssets`` requests and continue to iterate - through the ``governed_assets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` - 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[..., asset_service.AnalyzeOrgPolicyGovernedAssetsResponse], - request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, - response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, - *, - 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.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest): - The initial request object. - response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse): - 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: - 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[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset]: - for page in self.pages: - yield from page.governed_assets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class AnalyzeOrgPolicyGovernedAssetsAsyncPager: - """A pager for iterating through ``analyze_org_policy_governed_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``governed_assets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``AnalyzeOrgPolicyGovernedAssets`` requests and continue to iterate - through the ``governed_assets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse` - 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[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]], - request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, - response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, - *, - 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.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest): - The initial request object. - response (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse): - 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: - 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[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset]: - async def async_generator(): - async for page in self.pages: - for response in page.governed_assets: - 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/asset_v1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py deleted file mode 100644 index c34a5f8f..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AssetServiceTransport -from .grpc import AssetServiceGrpcTransport -from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .rest import AssetServiceRestTransport -from .rest import AssetServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AssetServiceRestTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', - 'AssetServiceRestTransport', - 'AssetServiceRestInterceptor', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py deleted file mode 100644 index c2b0fe0d..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py +++ /dev/null @@ -1,580 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.asset_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.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AssetServiceTransport(abc.ABC): - """Abstract transport class for AssetService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudasset.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.export_assets: gapic_v1.method.wrap_method( - self.export_assets, - default_timeout=60.0, - client_info=client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.batch_get_assets_history: gapic_v1.method.wrap_method( - self.batch_get_assets_history, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_feed: gapic_v1.method.wrap_method( - self.create_feed, - default_timeout=60.0, - client_info=client_info, - ), - self.get_feed: gapic_v1.method.wrap_method( - self.get_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_feeds: gapic_v1.method.wrap_method( - self.list_feeds, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_feed: gapic_v1.method.wrap_method( - self.update_feed, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_feed: gapic_v1.method.wrap_method( - self.delete_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.search_all_resources: gapic_v1.method.wrap_method( - self.search_all_resources, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.search_all_iam_policies: gapic_v1.method.wrap_method( - self.search_all_iam_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=30.0, - ), - default_timeout=30.0, - client_info=client_info, - ), - self.analyze_iam_policy: gapic_v1.method.wrap_method( - self.analyze_iam_policy, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.analyze_iam_policy_longrunning: gapic_v1.method.wrap_method( - self.analyze_iam_policy_longrunning, - default_timeout=60.0, - client_info=client_info, - ), - self.analyze_move: gapic_v1.method.wrap_method( - self.analyze_move, - default_timeout=None, - client_info=client_info, - ), - self.query_assets: gapic_v1.method.wrap_method( - self.query_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=200.0, - ), - default_timeout=200.0, - client_info=client_info, - ), - self.create_saved_query: gapic_v1.method.wrap_method( - self.create_saved_query, - default_timeout=60.0, - client_info=client_info, - ), - self.get_saved_query: gapic_v1.method.wrap_method( - self.get_saved_query, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_saved_queries: gapic_v1.method.wrap_method( - self.list_saved_queries, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_saved_query: gapic_v1.method.wrap_method( - self.update_saved_query, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_saved_query: gapic_v1.method.wrap_method( - self.delete_saved_query, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.batch_get_effective_iam_policies: gapic_v1.method.wrap_method( - self.batch_get_effective_iam_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=300.0, - ), - default_timeout=300.0, - client_info=client_info, - ), - self.analyze_org_policies: gapic_v1.method.wrap_method( - self.analyze_org_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.analyze_org_policy_governed_containers: gapic_v1.method.wrap_method( - self.analyze_org_policy_governed_containers, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.analyze_org_policy_governed_assets: gapic_v1.method.wrap_method( - self.analyze_org_policy_governed_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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 operations_client(self): - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - Union[ - asset_service.ListAssetsResponse, - Awaitable[asset_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - Union[ - asset_service.BatchGetAssetsHistoryResponse, - Awaitable[asset_service.BatchGetAssetsHistoryResponse] - ]]: - raise NotImplementedError() - - @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: - raise NotImplementedError() - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: - raise NotImplementedError() - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - Union[ - asset_service.ListFeedsResponse, - Awaitable[asset_service.ListFeedsResponse] - ]]: - raise NotImplementedError() - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: - raise NotImplementedError() - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - Union[ - asset_service.SearchAllResourcesResponse, - Awaitable[asset_service.SearchAllResourcesResponse] - ]]: - raise NotImplementedError() - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - Union[ - asset_service.SearchAllIamPoliciesResponse, - Awaitable[asset_service.SearchAllIamPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - Union[ - asset_service.AnalyzeIamPolicyResponse, - Awaitable[asset_service.AnalyzeIamPolicyResponse] - ]]: - raise NotImplementedError() - - @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - Union[ - asset_service.AnalyzeMoveResponse, - Awaitable[asset_service.AnalyzeMoveResponse] - ]]: - raise NotImplementedError() - - @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - Union[ - asset_service.QueryAssetsResponse, - Awaitable[asset_service.QueryAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: - raise NotImplementedError() - - @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: - raise NotImplementedError() - - @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - Union[ - asset_service.ListSavedQueriesResponse, - Awaitable[asset_service.ListSavedQueriesResponse] - ]]: - raise NotImplementedError() - - @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - Union[ - asset_service.SavedQuery, - Awaitable[asset_service.SavedQuery] - ]]: - raise NotImplementedError() - - @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - Union[ - asset_service.BatchGetEffectiveIamPoliciesResponse, - Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - Union[ - asset_service.AnalyzeOrgPoliciesResponse, - Awaitable[asset_service.AnalyzeOrgPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse] - ]]: - raise NotImplementedError() - - @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - Union[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse, - Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AssetServiceTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py deleted file mode 100644 index 2dfa44ec..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,959 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO - - -class AssetServiceGrpcTransport(AssetServiceTransport): - """gRPC backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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 export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - operations_pb2.Operation]: - r"""Return a callable for the export assets method over gRPC. - - Exports assets with time and resource types to a given Cloud - Storage location/BigQuery table. For Cloud Storage location - destinations, the output format is newline-delimited JSON. Each - line represents a - [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in - the JSON format; for BigQuery table destinations, the output - table stores the fields in asset Protobuf as columns. This API - implements the - [google.longrunning.Operation][google.longrunning.Operation] - API, which allows you to keep track of the export. We recommend - intervals of at least 2 seconds with exponential retry to poll - the export operation result. For regular-size resource parent, - the export operation usually finishes within 5 minutes. - - Returns: - Callable[[~.ExportAssetsRequest], - ~.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 'export_assets' not in self._stubs: - self._stubs['export_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ExportAssets', - request_serializer=asset_service.ExportAssetsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_assets'] - - @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - asset_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists assets with time and resource types and returns - paged results in response. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - 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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListAssets', - request_serializer=asset_service.ListAssetsRequest.serialize, - response_deserializer=asset_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - asset_service.BatchGetAssetsHistoryResponse]: - r"""Return a callable for the batch get assets history method over gRPC. - - Batch gets the update history of assets that overlap a time - window. For IAM_POLICY content, this API outputs history when - the asset and its attached IAM POLICY both exist. This can - create gaps in the output history. Otherwise, this API outputs - history with asset in both non-delete or deleted status. If a - specified asset does not exist, this API returns an - INVALID_ARGUMENT error. - - Returns: - Callable[[~.BatchGetAssetsHistoryRequest], - ~.BatchGetAssetsHistoryResponse]: - 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 'batch_get_assets_history' not in self._stubs: - self._stubs['batch_get_assets_history'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory', - request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, - response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, - ) - return self._stubs['batch_get_assets_history'] - - @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - asset_service.Feed]: - r"""Return a callable for the create feed method over gRPC. - - Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Returns: - Callable[[~.CreateFeedRequest], - ~.Feed]: - 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_feed' not in self._stubs: - self._stubs['create_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/CreateFeed', - request_serializer=asset_service.CreateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['create_feed'] - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - asset_service.Feed]: - r"""Return a callable for the get feed method over gRPC. - - Gets details about an asset feed. - - Returns: - Callable[[~.GetFeedRequest], - ~.Feed]: - 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_feed' not in self._stubs: - self._stubs['get_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/GetFeed', - request_serializer=asset_service.GetFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['get_feed'] - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - asset_service.ListFeedsResponse]: - r"""Return a callable for the list feeds method over gRPC. - - Lists all asset feeds in a parent - project/folder/organization. - - Returns: - Callable[[~.ListFeedsRequest], - ~.ListFeedsResponse]: - 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_feeds' not in self._stubs: - self._stubs['list_feeds'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListFeeds', - request_serializer=asset_service.ListFeedsRequest.serialize, - response_deserializer=asset_service.ListFeedsResponse.deserialize, - ) - return self._stubs['list_feeds'] - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - asset_service.Feed]: - r"""Return a callable for the update feed method over gRPC. - - Updates an asset feed configuration. - - Returns: - Callable[[~.UpdateFeedRequest], - ~.Feed]: - 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_feed' not in self._stubs: - self._stubs['update_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/UpdateFeed', - request_serializer=asset_service.UpdateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['update_feed'] - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete feed method over gRPC. - - Deletes an asset feed. - - Returns: - Callable[[~.DeleteFeedRequest], - ~.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_feed' not in self._stubs: - self._stubs['delete_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/DeleteFeed', - request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_feed'] - - @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - asset_service.SearchAllResourcesResponse]: - r"""Return a callable for the search all resources method over gRPC. - - Searches all Google Cloud resources within the specified scope, - such as a project, folder, or organization. The caller must be - granted the ``cloudasset.assets.searchAllResources`` permission - on the desired scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllResourcesRequest], - ~.SearchAllResourcesResponse]: - 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 'search_all_resources' not in self._stubs: - self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/SearchAllResources', - request_serializer=asset_service.SearchAllResourcesRequest.serialize, - response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, - ) - return self._stubs['search_all_resources'] - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - asset_service.SearchAllIamPoliciesResponse]: - r"""Return a callable for the search all iam policies method over gRPC. - - Searches all IAM policies within the specified scope, such as a - project, folder, or organization. The caller must be granted the - ``cloudasset.assets.searchAllIamPolicies`` permission on the - desired scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllIamPoliciesRequest], - ~.SearchAllIamPoliciesResponse]: - 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 'search_all_iam_policies' not in self._stubs: - self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/SearchAllIamPolicies', - request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, - response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, - ) - return self._stubs['search_all_iam_policies'] - - @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - asset_service.AnalyzeIamPolicyResponse]: - r"""Return a callable for the analyze iam policy method over gRPC. - - Analyzes IAM policies to answer which identities have - what accesses on which resources. - - Returns: - Callable[[~.AnalyzeIamPolicyRequest], - ~.AnalyzeIamPolicyResponse]: - 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 'analyze_iam_policy' not in self._stubs: - self._stubs['analyze_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy', - request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, - response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, - ) - return self._stubs['analyze_iam_policy'] - - @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - operations_pb2.Operation]: - r"""Return a callable for the analyze iam policy longrunning method over gRPC. - - Analyzes IAM policies asynchronously to answer which identities - have what accesses on which resources, and writes the analysis - results to a Google Cloud Storage or a BigQuery destination. For - Cloud Storage destination, the output format is the JSON format - that represents a - [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. - This method implements the - [google.longrunning.Operation][google.longrunning.Operation], - which allows you to track the operation status. We recommend - intervals of at least 2 seconds with exponential backoff retry - to poll the operation result. The metadata contains the metadata - for the long-running operation. - - Returns: - Callable[[~.AnalyzeIamPolicyLongrunningRequest], - ~.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 'analyze_iam_policy_longrunning' not in self._stubs: - self._stubs['analyze_iam_policy_longrunning'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning', - request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['analyze_iam_policy_longrunning'] - - @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - asset_service.AnalyzeMoveResponse]: - r"""Return a callable for the analyze move method over gRPC. - - Analyze moving a resource to a specified destination - without kicking off the actual move. The analysis is - best effort depending on the user's permissions of - viewing different hierarchical policies and - configurations. The policies and configuration are - subject to change before the actual resource migration - takes place. - - Returns: - Callable[[~.AnalyzeMoveRequest], - ~.AnalyzeMoveResponse]: - 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 'analyze_move' not in self._stubs: - self._stubs['analyze_move'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeMove', - request_serializer=asset_service.AnalyzeMoveRequest.serialize, - response_deserializer=asset_service.AnalyzeMoveResponse.deserialize, - ) - return self._stubs['analyze_move'] - - @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - asset_service.QueryAssetsResponse]: - r"""Return a callable for the query assets method over gRPC. - - Issue a job that queries assets using a SQL statement compatible - with `BigQuery - SQL `__. - - If the query execution finishes within timeout and there's no - pagination, the full query results will be returned in the - ``QueryAssetsResponse``. - - Otherwise, full query results can be obtained by issuing extra - requests with the ``job_reference`` from the a previous - ``QueryAssets`` call. - - Note, the query result has approximately 10 GB limitation - enforced by - `BigQuery `__. - Queries return larger results will result in errors. - - Returns: - Callable[[~.QueryAssetsRequest], - ~.QueryAssetsResponse]: - 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 'query_assets' not in self._stubs: - self._stubs['query_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/QueryAssets', - request_serializer=asset_service.QueryAssetsRequest.serialize, - response_deserializer=asset_service.QueryAssetsResponse.deserialize, - ) - return self._stubs['query_assets'] - - @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - asset_service.SavedQuery]: - r"""Return a callable for the create saved query method over gRPC. - - Creates a saved query in a parent - project/folder/organization. - - Returns: - Callable[[~.CreateSavedQueryRequest], - ~.SavedQuery]: - 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_saved_query' not in self._stubs: - self._stubs['create_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/CreateSavedQuery', - request_serializer=asset_service.CreateSavedQueryRequest.serialize, - response_deserializer=asset_service.SavedQuery.deserialize, - ) - return self._stubs['create_saved_query'] - - @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - asset_service.SavedQuery]: - r"""Return a callable for the get saved query method over gRPC. - - Gets details about a saved query. - - Returns: - Callable[[~.GetSavedQueryRequest], - ~.SavedQuery]: - 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_saved_query' not in self._stubs: - self._stubs['get_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/GetSavedQuery', - request_serializer=asset_service.GetSavedQueryRequest.serialize, - response_deserializer=asset_service.SavedQuery.deserialize, - ) - return self._stubs['get_saved_query'] - - @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - asset_service.ListSavedQueriesResponse]: - r"""Return a callable for the list saved queries method over gRPC. - - Lists all saved queries in a parent - project/folder/organization. - - Returns: - Callable[[~.ListSavedQueriesRequest], - ~.ListSavedQueriesResponse]: - 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_saved_queries' not in self._stubs: - self._stubs['list_saved_queries'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListSavedQueries', - request_serializer=asset_service.ListSavedQueriesRequest.serialize, - response_deserializer=asset_service.ListSavedQueriesResponse.deserialize, - ) - return self._stubs['list_saved_queries'] - - @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - asset_service.SavedQuery]: - r"""Return a callable for the update saved query method over gRPC. - - Updates a saved query. - - Returns: - Callable[[~.UpdateSavedQueryRequest], - ~.SavedQuery]: - 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_saved_query' not in self._stubs: - self._stubs['update_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/UpdateSavedQuery', - request_serializer=asset_service.UpdateSavedQueryRequest.serialize, - response_deserializer=asset_service.SavedQuery.deserialize, - ) - return self._stubs['update_saved_query'] - - @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete saved query method over gRPC. - - Deletes a saved query. - - Returns: - Callable[[~.DeleteSavedQueryRequest], - ~.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_saved_query' not in self._stubs: - self._stubs['delete_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/DeleteSavedQuery', - request_serializer=asset_service.DeleteSavedQueryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_saved_query'] - - @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - asset_service.BatchGetEffectiveIamPoliciesResponse]: - r"""Return a callable for the batch get effective iam - policies method over gRPC. - - Gets effective IAM policies for a batch of resources. - - Returns: - Callable[[~.BatchGetEffectiveIamPoliciesRequest], - ~.BatchGetEffectiveIamPoliciesResponse]: - 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 'batch_get_effective_iam_policies' not in self._stubs: - self._stubs['batch_get_effective_iam_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies', - request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, - response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, - ) - return self._stubs['batch_get_effective_iam_policies'] - - @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - asset_service.AnalyzeOrgPoliciesResponse]: - r"""Return a callable for the analyze org policies method over gRPC. - - Analyzes organization policies under a scope. - - Returns: - Callable[[~.AnalyzeOrgPoliciesRequest], - ~.AnalyzeOrgPoliciesResponse]: - 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 'analyze_org_policies' not in self._stubs: - self._stubs['analyze_org_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies', - request_serializer=asset_service.AnalyzeOrgPoliciesRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPoliciesResponse.deserialize, - ) - return self._stubs['analyze_org_policies'] - - @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: - r"""Return a callable for the analyze org policy governed - containers method over gRPC. - - Analyzes organization policies governed containers - (projects, folders or organization) under a scope. - - Returns: - Callable[[~.AnalyzeOrgPolicyGovernedContainersRequest], - ~.AnalyzeOrgPolicyGovernedContainersResponse]: - 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 'analyze_org_policy_governed_containers' not in self._stubs: - self._stubs['analyze_org_policy_governed_containers'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers', - request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, - ) - return self._stubs['analyze_org_policy_governed_containers'] - - @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: - r"""Return a callable for the analyze org policy governed - assets method over gRPC. - - Analyzes organization policies governed assets (Google Cloud - resources or policies) under a scope. This RPC supports custom - constraints and the following 10 canned constraints: - - - storage.uniformBucketLevelAccess - - iam.disableServiceAccountKeyCreation - - iam.allowedPolicyMemberDomains - - compute.vmExternalIpAccess - - appengine.enforceServiceAccountActAsCheck - - gcp.resourceLocations - - compute.trustedImageProjects - - compute.skipDefaultNetworkCreation - - compute.requireOsLogin - - compute.disableNestedVirtualization - - This RPC only returns either resources of types supported by - `searchable asset - types `__, - or IAM policies. - - Returns: - Callable[[~.AnalyzeOrgPolicyGovernedAssetsRequest], - ~.AnalyzeOrgPolicyGovernedAssetsResponse]: - 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 'analyze_org_policy_governed_assets' not in self._stubs: - self._stubs['analyze_org_policy_governed_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets', - request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, - ) - return self._stubs['analyze_org_policy_governed_assets'] - - def close(self): - self.grpc_channel.close() - - @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 kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AssetServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py deleted file mode 100644 index 373e65ad..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,958 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.asset_v1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import empty_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AssetServiceGrpcTransport - - -class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): - """gRPC AsyncIO backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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 export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export assets method over gRPC. - - Exports assets with time and resource types to a given Cloud - Storage location/BigQuery table. For Cloud Storage location - destinations, the output format is newline-delimited JSON. Each - line represents a - [google.cloud.asset.v1.Asset][google.cloud.asset.v1.Asset] in - the JSON format; for BigQuery table destinations, the output - table stores the fields in asset Protobuf as columns. This API - implements the - [google.longrunning.Operation][google.longrunning.Operation] - API, which allows you to keep track of the export. We recommend - intervals of at least 2 seconds with exponential retry to poll - the export operation result. For regular-size resource parent, - the export operation usually finishes within 5 minutes. - - Returns: - Callable[[~.ExportAssetsRequest], - 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 'export_assets' not in self._stubs: - self._stubs['export_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ExportAssets', - request_serializer=asset_service.ExportAssetsRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_assets'] - - @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - Awaitable[asset_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists assets with time and resource types and returns - paged results in response. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - 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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListAssets', - request_serializer=asset_service.ListAssetsRequest.serialize, - response_deserializer=asset_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - Awaitable[asset_service.BatchGetAssetsHistoryResponse]]: - r"""Return a callable for the batch get assets history method over gRPC. - - Batch gets the update history of assets that overlap a time - window. For IAM_POLICY content, this API outputs history when - the asset and its attached IAM POLICY both exist. This can - create gaps in the output history. Otherwise, this API outputs - history with asset in both non-delete or deleted status. If a - specified asset does not exist, this API returns an - INVALID_ARGUMENT error. - - Returns: - Callable[[~.BatchGetAssetsHistoryRequest], - Awaitable[~.BatchGetAssetsHistoryResponse]]: - 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 'batch_get_assets_history' not in self._stubs: - self._stubs['batch_get_assets_history'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/BatchGetAssetsHistory', - request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, - response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, - ) - return self._stubs['batch_get_assets_history'] - - @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - Awaitable[asset_service.Feed]]: - r"""Return a callable for the create feed method over gRPC. - - Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Returns: - Callable[[~.CreateFeedRequest], - Awaitable[~.Feed]]: - 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_feed' not in self._stubs: - self._stubs['create_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/CreateFeed', - request_serializer=asset_service.CreateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['create_feed'] - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - Awaitable[asset_service.Feed]]: - r"""Return a callable for the get feed method over gRPC. - - Gets details about an asset feed. - - Returns: - Callable[[~.GetFeedRequest], - Awaitable[~.Feed]]: - 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_feed' not in self._stubs: - self._stubs['get_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/GetFeed', - request_serializer=asset_service.GetFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['get_feed'] - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - Awaitable[asset_service.ListFeedsResponse]]: - r"""Return a callable for the list feeds method over gRPC. - - Lists all asset feeds in a parent - project/folder/organization. - - Returns: - Callable[[~.ListFeedsRequest], - Awaitable[~.ListFeedsResponse]]: - 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_feeds' not in self._stubs: - self._stubs['list_feeds'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListFeeds', - request_serializer=asset_service.ListFeedsRequest.serialize, - response_deserializer=asset_service.ListFeedsResponse.deserialize, - ) - return self._stubs['list_feeds'] - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - Awaitable[asset_service.Feed]]: - r"""Return a callable for the update feed method over gRPC. - - Updates an asset feed configuration. - - Returns: - Callable[[~.UpdateFeedRequest], - Awaitable[~.Feed]]: - 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_feed' not in self._stubs: - self._stubs['update_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/UpdateFeed', - request_serializer=asset_service.UpdateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['update_feed'] - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete feed method over gRPC. - - Deletes an asset feed. - - Returns: - Callable[[~.DeleteFeedRequest], - 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_feed' not in self._stubs: - self._stubs['delete_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/DeleteFeed', - request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_feed'] - - @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - Awaitable[asset_service.SearchAllResourcesResponse]]: - r"""Return a callable for the search all resources method over gRPC. - - Searches all Google Cloud resources within the specified scope, - such as a project, folder, or organization. The caller must be - granted the ``cloudasset.assets.searchAllResources`` permission - on the desired scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllResourcesRequest], - Awaitable[~.SearchAllResourcesResponse]]: - 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 'search_all_resources' not in self._stubs: - self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/SearchAllResources', - request_serializer=asset_service.SearchAllResourcesRequest.serialize, - response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, - ) - return self._stubs['search_all_resources'] - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - Awaitable[asset_service.SearchAllIamPoliciesResponse]]: - r"""Return a callable for the search all iam policies method over gRPC. - - Searches all IAM policies within the specified scope, such as a - project, folder, or organization. The caller must be granted the - ``cloudasset.assets.searchAllIamPolicies`` permission on the - desired scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllIamPoliciesRequest], - Awaitable[~.SearchAllIamPoliciesResponse]]: - 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 'search_all_iam_policies' not in self._stubs: - self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/SearchAllIamPolicies', - request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, - response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, - ) - return self._stubs['search_all_iam_policies'] - - @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - Awaitable[asset_service.AnalyzeIamPolicyResponse]]: - r"""Return a callable for the analyze iam policy method over gRPC. - - Analyzes IAM policies to answer which identities have - what accesses on which resources. - - Returns: - Callable[[~.AnalyzeIamPolicyRequest], - Awaitable[~.AnalyzeIamPolicyResponse]]: - 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 'analyze_iam_policy' not in self._stubs: - self._stubs['analyze_iam_policy'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicy', - request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, - response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, - ) - return self._stubs['analyze_iam_policy'] - - @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the analyze iam policy longrunning method over gRPC. - - Analyzes IAM policies asynchronously to answer which identities - have what accesses on which resources, and writes the analysis - results to a Google Cloud Storage or a BigQuery destination. For - Cloud Storage destination, the output format is the JSON format - that represents a - [AnalyzeIamPolicyResponse][google.cloud.asset.v1.AnalyzeIamPolicyResponse]. - This method implements the - [google.longrunning.Operation][google.longrunning.Operation], - which allows you to track the operation status. We recommend - intervals of at least 2 seconds with exponential backoff retry - to poll the operation result. The metadata contains the metadata - for the long-running operation. - - Returns: - Callable[[~.AnalyzeIamPolicyLongrunningRequest], - 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 'analyze_iam_policy_longrunning' not in self._stubs: - self._stubs['analyze_iam_policy_longrunning'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning', - request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['analyze_iam_policy_longrunning'] - - @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - Awaitable[asset_service.AnalyzeMoveResponse]]: - r"""Return a callable for the analyze move method over gRPC. - - Analyze moving a resource to a specified destination - without kicking off the actual move. The analysis is - best effort depending on the user's permissions of - viewing different hierarchical policies and - configurations. The policies and configuration are - subject to change before the actual resource migration - takes place. - - Returns: - Callable[[~.AnalyzeMoveRequest], - Awaitable[~.AnalyzeMoveResponse]]: - 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 'analyze_move' not in self._stubs: - self._stubs['analyze_move'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeMove', - request_serializer=asset_service.AnalyzeMoveRequest.serialize, - response_deserializer=asset_service.AnalyzeMoveResponse.deserialize, - ) - return self._stubs['analyze_move'] - - @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - Awaitable[asset_service.QueryAssetsResponse]]: - r"""Return a callable for the query assets method over gRPC. - - Issue a job that queries assets using a SQL statement compatible - with `BigQuery - SQL `__. - - If the query execution finishes within timeout and there's no - pagination, the full query results will be returned in the - ``QueryAssetsResponse``. - - Otherwise, full query results can be obtained by issuing extra - requests with the ``job_reference`` from the a previous - ``QueryAssets`` call. - - Note, the query result has approximately 10 GB limitation - enforced by - `BigQuery `__. - Queries return larger results will result in errors. - - Returns: - Callable[[~.QueryAssetsRequest], - Awaitable[~.QueryAssetsResponse]]: - 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 'query_assets' not in self._stubs: - self._stubs['query_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/QueryAssets', - request_serializer=asset_service.QueryAssetsRequest.serialize, - response_deserializer=asset_service.QueryAssetsResponse.deserialize, - ) - return self._stubs['query_assets'] - - @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - Awaitable[asset_service.SavedQuery]]: - r"""Return a callable for the create saved query method over gRPC. - - Creates a saved query in a parent - project/folder/organization. - - Returns: - Callable[[~.CreateSavedQueryRequest], - Awaitable[~.SavedQuery]]: - 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_saved_query' not in self._stubs: - self._stubs['create_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/CreateSavedQuery', - request_serializer=asset_service.CreateSavedQueryRequest.serialize, - response_deserializer=asset_service.SavedQuery.deserialize, - ) - return self._stubs['create_saved_query'] - - @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - Awaitable[asset_service.SavedQuery]]: - r"""Return a callable for the get saved query method over gRPC. - - Gets details about a saved query. - - Returns: - Callable[[~.GetSavedQueryRequest], - Awaitable[~.SavedQuery]]: - 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_saved_query' not in self._stubs: - self._stubs['get_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/GetSavedQuery', - request_serializer=asset_service.GetSavedQueryRequest.serialize, - response_deserializer=asset_service.SavedQuery.deserialize, - ) - return self._stubs['get_saved_query'] - - @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - Awaitable[asset_service.ListSavedQueriesResponse]]: - r"""Return a callable for the list saved queries method over gRPC. - - Lists all saved queries in a parent - project/folder/organization. - - Returns: - Callable[[~.ListSavedQueriesRequest], - Awaitable[~.ListSavedQueriesResponse]]: - 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_saved_queries' not in self._stubs: - self._stubs['list_saved_queries'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/ListSavedQueries', - request_serializer=asset_service.ListSavedQueriesRequest.serialize, - response_deserializer=asset_service.ListSavedQueriesResponse.deserialize, - ) - return self._stubs['list_saved_queries'] - - @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - Awaitable[asset_service.SavedQuery]]: - r"""Return a callable for the update saved query method over gRPC. - - Updates a saved query. - - Returns: - Callable[[~.UpdateSavedQueryRequest], - Awaitable[~.SavedQuery]]: - 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_saved_query' not in self._stubs: - self._stubs['update_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/UpdateSavedQuery', - request_serializer=asset_service.UpdateSavedQueryRequest.serialize, - response_deserializer=asset_service.SavedQuery.deserialize, - ) - return self._stubs['update_saved_query'] - - @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete saved query method over gRPC. - - Deletes a saved query. - - Returns: - Callable[[~.DeleteSavedQueryRequest], - 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_saved_query' not in self._stubs: - self._stubs['delete_saved_query'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/DeleteSavedQuery', - request_serializer=asset_service.DeleteSavedQueryRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_saved_query'] - - @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - Awaitable[asset_service.BatchGetEffectiveIamPoliciesResponse]]: - r"""Return a callable for the batch get effective iam - policies method over gRPC. - - Gets effective IAM policies for a batch of resources. - - Returns: - Callable[[~.BatchGetEffectiveIamPoliciesRequest], - Awaitable[~.BatchGetEffectiveIamPoliciesResponse]]: - 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 'batch_get_effective_iam_policies' not in self._stubs: - self._stubs['batch_get_effective_iam_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/BatchGetEffectiveIamPolicies', - request_serializer=asset_service.BatchGetEffectiveIamPoliciesRequest.serialize, - response_deserializer=asset_service.BatchGetEffectiveIamPoliciesResponse.deserialize, - ) - return self._stubs['batch_get_effective_iam_policies'] - - @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - Awaitable[asset_service.AnalyzeOrgPoliciesResponse]]: - r"""Return a callable for the analyze org policies method over gRPC. - - Analyzes organization policies under a scope. - - Returns: - Callable[[~.AnalyzeOrgPoliciesRequest], - Awaitable[~.AnalyzeOrgPoliciesResponse]]: - 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 'analyze_org_policies' not in self._stubs: - self._stubs['analyze_org_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicies', - request_serializer=asset_service.AnalyzeOrgPoliciesRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPoliciesResponse.deserialize, - ) - return self._stubs['analyze_org_policies'] - - @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - Awaitable[asset_service.AnalyzeOrgPolicyGovernedContainersResponse]]: - r"""Return a callable for the analyze org policy governed - containers method over gRPC. - - Analyzes organization policies governed containers - (projects, folders or organization) under a scope. - - Returns: - Callable[[~.AnalyzeOrgPolicyGovernedContainersRequest], - Awaitable[~.AnalyzeOrgPolicyGovernedContainersResponse]]: - 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 'analyze_org_policy_governed_containers' not in self._stubs: - self._stubs['analyze_org_policy_governed_containers'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedContainers', - request_serializer=asset_service.AnalyzeOrgPolicyGovernedContainersRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedContainersResponse.deserialize, - ) - return self._stubs['analyze_org_policy_governed_containers'] - - @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - Awaitable[asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]]: - r"""Return a callable for the analyze org policy governed - assets method over gRPC. - - Analyzes organization policies governed assets (Google Cloud - resources or policies) under a scope. This RPC supports custom - constraints and the following 10 canned constraints: - - - storage.uniformBucketLevelAccess - - iam.disableServiceAccountKeyCreation - - iam.allowedPolicyMemberDomains - - compute.vmExternalIpAccess - - appengine.enforceServiceAccountActAsCheck - - gcp.resourceLocations - - compute.trustedImageProjects - - compute.skipDefaultNetworkCreation - - compute.requireOsLogin - - compute.disableNestedVirtualization - - This RPC only returns either resources of types supported by - `searchable asset - types `__, - or IAM policies. - - Returns: - Callable[[~.AnalyzeOrgPolicyGovernedAssetsRequest], - Awaitable[~.AnalyzeOrgPolicyGovernedAssetsResponse]]: - 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 'analyze_org_policy_governed_assets' not in self._stubs: - self._stubs['analyze_org_policy_governed_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1.AssetService/AnalyzeOrgPolicyGovernedAssets', - request_serializer=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.serialize, - response_deserializer=asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.deserialize, - ) - return self._stubs['analyze_org_policy_governed_assets'] - - def close(self): - return self.grpc_channel.close() - - @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"] - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py deleted file mode 100644 index a5b80a83..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/rest.py +++ /dev/null @@ -1,2899 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -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 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.asset_v1.types import asset_service -from google.protobuf import empty_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: - """Interceptor for AssetService. - - 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 AssetServiceRestTransport. - - .. code-block:: python - class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): - def pre_analyze_iam_policy(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_iam_policy(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_iam_policy_longrunning(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_iam_policy_longrunning(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_move(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_move(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_org_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_org_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_org_policy_governed_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_org_policy_governed_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_analyze_org_policy_governed_containers(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_analyze_org_policy_governed_containers(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_get_assets_history(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_get_assets_history(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_batch_get_effective_iam_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_batch_get_effective_iam_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_feed(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_saved_query(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_saved_query(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_delete_saved_query(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_export_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_export_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_feed(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_saved_query(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_saved_query(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_feeds(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_feeds(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_saved_queries(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_saved_queries(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_query_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_query_assets(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_all_iam_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_all_iam_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_all_resources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_all_resources(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_feed(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_saved_query(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_saved_query(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) - client = AssetServiceClient(transport=transport) - - - """ - def pre_analyze_iam_policy(self, request: asset_service.AnalyzeIamPolicyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_analyze_iam_policy(self, response: asset_service.AnalyzeIamPolicyResponse) -> asset_service.AnalyzeIamPolicyResponse: - """Post-rpc interceptor for analyze_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_analyze_iam_policy_longrunning(self, request: asset_service.AnalyzeIamPolicyLongrunningRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeIamPolicyLongrunningRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_iam_policy_longrunning - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_analyze_iam_policy_longrunning(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for analyze_iam_policy_longrunning - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_analyze_move(self, request: asset_service.AnalyzeMoveRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeMoveRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_move - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_analyze_move(self, response: asset_service.AnalyzeMoveResponse) -> asset_service.AnalyzeMoveResponse: - """Post-rpc interceptor for analyze_move - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_analyze_org_policies(self, request: asset_service.AnalyzeOrgPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeOrgPoliciesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_org_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_analyze_org_policies(self, response: asset_service.AnalyzeOrgPoliciesResponse) -> asset_service.AnalyzeOrgPoliciesResponse: - """Post-rpc interceptor for analyze_org_policies - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_analyze_org_policy_governed_assets(self, request: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_org_policy_governed_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_analyze_org_policy_governed_assets(self, response: asset_service.AnalyzeOrgPolicyGovernedAssetsResponse) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: - """Post-rpc interceptor for analyze_org_policy_governed_assets - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_analyze_org_policy_governed_containers(self, request: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.AnalyzeOrgPolicyGovernedContainersRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for analyze_org_policy_governed_containers - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_analyze_org_policy_governed_containers(self, response: asset_service.AnalyzeOrgPolicyGovernedContainersResponse) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: - """Post-rpc interceptor for analyze_org_policy_governed_containers - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_batch_get_assets_history(self, request: asset_service.BatchGetAssetsHistoryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.BatchGetAssetsHistoryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_get_assets_history - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_batch_get_assets_history(self, response: asset_service.BatchGetAssetsHistoryResponse) -> asset_service.BatchGetAssetsHistoryResponse: - """Post-rpc interceptor for batch_get_assets_history - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_batch_get_effective_iam_policies(self, request: asset_service.BatchGetEffectiveIamPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.BatchGetEffectiveIamPoliciesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for batch_get_effective_iam_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_batch_get_effective_iam_policies(self, response: asset_service.BatchGetEffectiveIamPoliciesResponse) -> asset_service.BatchGetEffectiveIamPoliciesResponse: - """Post-rpc interceptor for batch_get_effective_iam_policies - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_create_feed(self, request: asset_service.CreateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.CreateFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_create_feed(self, response: asset_service.Feed) -> asset_service.Feed: - """Post-rpc interceptor for create_feed - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_create_saved_query(self, request: asset_service.CreateSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.CreateSavedQueryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_saved_query - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_create_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: - """Post-rpc interceptor for create_saved_query - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_delete_feed(self, request: asset_service.DeleteFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.DeleteFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def pre_delete_saved_query(self, request: asset_service.DeleteSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.DeleteSavedQueryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_saved_query - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def pre_export_assets(self, request: asset_service.ExportAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ExportAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for export_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_export_assets(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for export_assets - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_get_feed(self, request: asset_service.GetFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.GetFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_get_feed(self, response: asset_service.Feed) -> asset_service.Feed: - """Post-rpc interceptor for get_feed - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_get_saved_query(self, request: asset_service.GetSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.GetSavedQueryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_saved_query - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_get_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: - """Post-rpc interceptor for get_saved_query - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_list_assets(self, request: asset_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_list_assets(self, response: asset_service.ListAssetsResponse) -> asset_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_list_feeds(self, request: asset_service.ListFeedsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListFeedsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_feeds - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_list_feeds(self, response: asset_service.ListFeedsResponse) -> asset_service.ListFeedsResponse: - """Post-rpc interceptor for list_feeds - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_list_saved_queries(self, request: asset_service.ListSavedQueriesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListSavedQueriesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_saved_queries - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_list_saved_queries(self, response: asset_service.ListSavedQueriesResponse) -> asset_service.ListSavedQueriesResponse: - """Post-rpc interceptor for list_saved_queries - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_query_assets(self, request: asset_service.QueryAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.QueryAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for query_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_query_assets(self, response: asset_service.QueryAssetsResponse) -> asset_service.QueryAssetsResponse: - """Post-rpc interceptor for query_assets - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_search_all_iam_policies(self, request: asset_service.SearchAllIamPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllIamPoliciesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_all_iam_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_search_all_iam_policies(self, response: asset_service.SearchAllIamPoliciesResponse) -> asset_service.SearchAllIamPoliciesResponse: - """Post-rpc interceptor for search_all_iam_policies - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_search_all_resources(self, request: asset_service.SearchAllResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllResourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_all_resources - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_search_all_resources(self, response: asset_service.SearchAllResourcesResponse) -> asset_service.SearchAllResourcesResponse: - """Post-rpc interceptor for search_all_resources - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_update_feed(self, request: asset_service.UpdateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.UpdateFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_update_feed(self, response: asset_service.Feed) -> asset_service.Feed: - """Post-rpc interceptor for update_feed - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_update_saved_query(self, request: asset_service.UpdateSavedQueryRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.UpdateSavedQueryRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_saved_query - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_update_saved_query(self, response: asset_service.SavedQuery) -> asset_service.SavedQuery: - """Post-rpc interceptor for update_saved_query - - Override in a subclass to manipulate the response - after it is returned by the AssetService 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 AssetService 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 AssetService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AssetServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AssetServiceRestInterceptor - - -class AssetServiceRestTransport(AssetServiceTransport): - """REST backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() - 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.GetOperation': [ - { - 'method': 'get', - 'uri': '/v1/{name=*/*/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 _AnalyzeIamPolicy(AssetServiceRestStub): - def __hash__(self): - return hash("AnalyzeIamPolicy") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "analysisQuery" : {}, } - - @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: asset_service.AnalyzeIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.AnalyzeIamPolicyResponse: - r"""Call the analyze iam policy method over HTTP. - - Args: - request (~.asset_service.AnalyzeIamPolicyRequest): - The request object. A request message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.AnalyzeIamPolicyResponse: - A response message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{analysis_query.scope=*/*}:analyzeIamPolicy', - }, - ] - request, metadata = self._interceptor.pre_analyze_iam_policy(request, metadata) - pb_request = asset_service.AnalyzeIamPolicyRequest.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 = asset_service.AnalyzeIamPolicyResponse() - pb_resp = asset_service.AnalyzeIamPolicyResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_iam_policy(resp) - return resp - - class _AnalyzeIamPolicyLongrunning(AssetServiceRestStub): - def __hash__(self): - return hash("AnalyzeIamPolicyLongrunning") - - __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: asset_service.AnalyzeIamPolicyLongrunningRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the analyze iam policy - longrunning method over HTTP. - - Args: - request (~.asset_service.AnalyzeIamPolicyLongrunningRequest): - The request object. A request message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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/{analysis_query.scope=*/*}:analyzeIamPolicyLongrunning', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_analyze_iam_policy_longrunning(request, metadata) - pb_request = asset_service.AnalyzeIamPolicyLongrunningRequest.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_analyze_iam_policy_longrunning(resp) - return resp - - class _AnalyzeMove(AssetServiceRestStub): - def __hash__(self): - return hash("AnalyzeMove") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "destinationParent" : "", } - - @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: asset_service.AnalyzeMoveRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.AnalyzeMoveResponse: - r"""Call the analyze move method over HTTP. - - Args: - request (~.asset_service.AnalyzeMoveRequest): - The request object. The request message for performing - resource move analysis. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.AnalyzeMoveResponse: - The response message for resource - move analysis. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=*/*}:analyzeMove', - }, - ] - request, metadata = self._interceptor.pre_analyze_move(request, metadata) - pb_request = asset_service.AnalyzeMoveRequest.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 = asset_service.AnalyzeMoveResponse() - pb_resp = asset_service.AnalyzeMoveResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_move(resp) - return resp - - class _AnalyzeOrgPolicies(AssetServiceRestStub): - def __hash__(self): - return hash("AnalyzeOrgPolicies") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "constraint" : "", } - - @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: asset_service.AnalyzeOrgPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.AnalyzeOrgPoliciesResponse: - r"""Call the analyze org policies method over HTTP. - - Args: - request (~.asset_service.AnalyzeOrgPoliciesRequest): - The request object. A request message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.AnalyzeOrgPoliciesResponse: - The response message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{scope=*/*}:analyzeOrgPolicies', - }, - ] - request, metadata = self._interceptor.pre_analyze_org_policies(request, metadata) - pb_request = asset_service.AnalyzeOrgPoliciesRequest.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 = asset_service.AnalyzeOrgPoliciesResponse() - pb_resp = asset_service.AnalyzeOrgPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_org_policies(resp) - return resp - - class _AnalyzeOrgPolicyGovernedAssets(AssetServiceRestStub): - def __hash__(self): - return hash("AnalyzeOrgPolicyGovernedAssets") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "constraint" : "", } - - @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: asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: - r"""Call the analyze org policy - governed assets method over HTTP. - - Args: - request (~.asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.AnalyzeOrgPolicyGovernedAssetsResponse: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{scope=*/*}:analyzeOrgPolicyGovernedAssets', - }, - ] - request, metadata = self._interceptor.pre_analyze_org_policy_governed_assets(request, metadata) - pb_request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() - pb_resp = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_org_policy_governed_assets(resp) - return resp - - class _AnalyzeOrgPolicyGovernedContainers(AssetServiceRestStub): - def __hash__(self): - return hash("AnalyzeOrgPolicyGovernedContainers") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "constraint" : "", } - - @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: asset_service.AnalyzeOrgPolicyGovernedContainersRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.AnalyzeOrgPolicyGovernedContainersResponse: - r"""Call the analyze org policy - governed containers method over HTTP. - - Args: - request (~.asset_service.AnalyzeOrgPolicyGovernedContainersRequest): - The request object. A request message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.AnalyzeOrgPolicyGovernedContainersResponse: - The response message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{scope=*/*}:analyzeOrgPolicyGovernedContainers', - }, - ] - request, metadata = self._interceptor.pre_analyze_org_policy_governed_containers(request, metadata) - pb_request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest.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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() - pb_resp = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_analyze_org_policy_governed_containers(resp) - return resp - - class _BatchGetAssetsHistory(AssetServiceRestStub): - def __hash__(self): - return hash("BatchGetAssetsHistory") - - __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: asset_service.BatchGetAssetsHistoryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.BatchGetAssetsHistoryResponse: - r"""Call the batch get assets history method over HTTP. - - Args: - request (~.asset_service.BatchGetAssetsHistoryRequest): - The request object. Batch get assets history request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.BatchGetAssetsHistoryResponse: - Batch get assets history response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=*/*}:batchGetAssetsHistory', - }, - ] - request, metadata = self._interceptor.pre_batch_get_assets_history(request, metadata) - pb_request = asset_service.BatchGetAssetsHistoryRequest.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 = asset_service.BatchGetAssetsHistoryResponse() - pb_resp = asset_service.BatchGetAssetsHistoryResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_get_assets_history(resp) - return resp - - class _BatchGetEffectiveIamPolicies(AssetServiceRestStub): - def __hash__(self): - return hash("BatchGetEffectiveIamPolicies") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "names" : "", } - - @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: asset_service.BatchGetEffectiveIamPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.BatchGetEffectiveIamPoliciesResponse: - r"""Call the batch get effective iam - policies method over HTTP. - - Args: - request (~.asset_service.BatchGetEffectiveIamPoliciesRequest): - The request object. A request message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.BatchGetEffectiveIamPoliciesResponse: - A response message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{scope=*/*}/effectiveIamPolicies:batchGet', - }, - ] - request, metadata = self._interceptor.pre_batch_get_effective_iam_policies(request, metadata) - pb_request = asset_service.BatchGetEffectiveIamPoliciesRequest.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 = asset_service.BatchGetEffectiveIamPoliciesResponse() - pb_resp = asset_service.BatchGetEffectiveIamPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_batch_get_effective_iam_policies(resp) - return resp - - class _CreateFeed(AssetServiceRestStub): - def __hash__(self): - return hash("CreateFeed") - - __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: asset_service.CreateFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.Feed: - r"""Call the create feed method over HTTP. - - Args: - request (~.asset_service.CreateFeedRequest): - The request object. Create asset feed request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=*/*}/feeds', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_create_feed(request, metadata) - pb_request = asset_service.CreateFeedRequest.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 = asset_service.Feed() - pb_resp = asset_service.Feed.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_feed(resp) - return resp - - class _CreateSavedQuery(AssetServiceRestStub): - def __hash__(self): - return hash("CreateSavedQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "savedQueryId" : "", } - - @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: asset_service.CreateSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.SavedQuery: - r"""Call the create saved query method over HTTP. - - Args: - request (~.asset_service.CreateSavedQueryRequest): - The request object. Request to create a saved query. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=*/*}/savedQueries', - 'body': 'saved_query', - }, - ] - request, metadata = self._interceptor.pre_create_saved_query(request, metadata) - pb_request = asset_service.CreateSavedQueryRequest.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 = asset_service.SavedQuery() - pb_resp = asset_service.SavedQuery.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_saved_query(resp) - return resp - - class _DeleteFeed(AssetServiceRestStub): - def __hash__(self): - return hash("DeleteFeed") - - __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: asset_service.DeleteFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete feed method over HTTP. - - Args: - request (~.asset_service.DeleteFeedRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1/{name=*/*/feeds/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_feed(request, metadata) - pb_request = asset_service.DeleteFeedRequest.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 _DeleteSavedQuery(AssetServiceRestStub): - def __hash__(self): - return hash("DeleteSavedQuery") - - __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: asset_service.DeleteSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete saved query method over HTTP. - - Args: - request (~.asset_service.DeleteSavedQueryRequest): - The request object. Request to delete a saved query. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be 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=*/*/savedQueries/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_saved_query(request, metadata) - pb_request = asset_service.DeleteSavedQueryRequest.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 _ExportAssets(AssetServiceRestStub): - def __hash__(self): - return hash("ExportAssets") - - __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: asset_service.ExportAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the export assets method over HTTP. - - Args: - request (~.asset_service.ExportAssetsRequest): - The request object. Export asset request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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=*/*}:exportAssets', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_export_assets(request, metadata) - pb_request = asset_service.ExportAssetsRequest.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_export_assets(resp) - return resp - - class _GetFeed(AssetServiceRestStub): - def __hash__(self): - return hash("GetFeed") - - __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: asset_service.GetFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.Feed: - r"""Call the get feed method over HTTP. - - Args: - request (~.asset_service.GetFeedRequest): - The request object. Get asset feed request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=*/*/feeds/*}', - }, - ] - request, metadata = self._interceptor.pre_get_feed(request, metadata) - pb_request = asset_service.GetFeedRequest.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 = asset_service.Feed() - pb_resp = asset_service.Feed.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_feed(resp) - return resp - - class _GetSavedQuery(AssetServiceRestStub): - def __hash__(self): - return hash("GetSavedQuery") - - __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: asset_service.GetSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.SavedQuery: - r"""Call the get saved query method over HTTP. - - Args: - request (~.asset_service.GetSavedQueryRequest): - The request object. Request to get a saved query. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=*/*/savedQueries/*}', - }, - ] - request, metadata = self._interceptor.pre_get_saved_query(request, metadata) - pb_request = asset_service.GetSavedQueryRequest.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 = asset_service.SavedQuery() - pb_resp = asset_service.SavedQuery.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_saved_query(resp) - return resp - - class _ListAssets(AssetServiceRestStub): - def __hash__(self): - return hash("ListAssets") - - __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: asset_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.asset_service.ListAssetsRequest): - The request object. ListAssets request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.ListAssetsResponse: - ListAssets response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=*/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = asset_service.ListAssetsRequest.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 = asset_service.ListAssetsResponse() - pb_resp = asset_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - class _ListFeeds(AssetServiceRestStub): - def __hash__(self): - return hash("ListFeeds") - - __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: asset_service.ListFeedsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.ListFeedsResponse: - r"""Call the list feeds method over HTTP. - - Args: - request (~.asset_service.ListFeedsRequest): - The request object. List asset feeds request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.ListFeedsResponse: - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=*/*}/feeds', - }, - ] - request, metadata = self._interceptor.pre_list_feeds(request, metadata) - pb_request = asset_service.ListFeedsRequest.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 = asset_service.ListFeedsResponse() - pb_resp = asset_service.ListFeedsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_feeds(resp) - return resp - - class _ListSavedQueries(AssetServiceRestStub): - def __hash__(self): - return hash("ListSavedQueries") - - __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: asset_service.ListSavedQueriesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.ListSavedQueriesResponse: - r"""Call the list saved queries method over HTTP. - - Args: - request (~.asset_service.ListSavedQueriesRequest): - The request object. Request to list saved queries. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.ListSavedQueriesResponse: - Response of listing saved queries. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=*/*}/savedQueries', - }, - ] - request, metadata = self._interceptor.pre_list_saved_queries(request, metadata) - pb_request = asset_service.ListSavedQueriesRequest.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 = asset_service.ListSavedQueriesResponse() - pb_resp = asset_service.ListSavedQueriesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_saved_queries(resp) - return resp - - class _QueryAssets(AssetServiceRestStub): - def __hash__(self): - return hash("QueryAssets") - - __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: asset_service.QueryAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.QueryAssetsResponse: - r"""Call the query assets method over HTTP. - - Args: - request (~.asset_service.QueryAssetsRequest): - The request object. QueryAssets request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.QueryAssetsResponse: - QueryAssets response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=*/*}:queryAssets', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_query_assets(request, metadata) - pb_request = asset_service.QueryAssetsRequest.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 = asset_service.QueryAssetsResponse() - pb_resp = asset_service.QueryAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_query_assets(resp) - return resp - - class _SearchAllIamPolicies(AssetServiceRestStub): - def __hash__(self): - return hash("SearchAllIamPolicies") - - __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: asset_service.SearchAllIamPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.SearchAllIamPoliciesResponse: - r"""Call the search all iam policies method over HTTP. - - Args: - request (~.asset_service.SearchAllIamPoliciesRequest): - The request object. Search all IAM policies request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.SearchAllIamPoliciesResponse: - Search all IAM policies response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{scope=*/*}:searchAllIamPolicies', - }, - ] - request, metadata = self._interceptor.pre_search_all_iam_policies(request, metadata) - pb_request = asset_service.SearchAllIamPoliciesRequest.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 = asset_service.SearchAllIamPoliciesResponse() - pb_resp = asset_service.SearchAllIamPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_all_iam_policies(resp) - return resp - - class _SearchAllResources(AssetServiceRestStub): - def __hash__(self): - return hash("SearchAllResources") - - __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: asset_service.SearchAllResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.SearchAllResourcesResponse: - r"""Call the search all resources method over HTTP. - - Args: - request (~.asset_service.SearchAllResourcesRequest): - The request object. Search all resources request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.SearchAllResourcesResponse: - Search all resources response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{scope=*/*}:searchAllResources', - }, - ] - request, metadata = self._interceptor.pre_search_all_resources(request, metadata) - pb_request = asset_service.SearchAllResourcesRequest.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 = asset_service.SearchAllResourcesResponse() - pb_resp = asset_service.SearchAllResourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_all_resources(resp) - return resp - - class _UpdateFeed(AssetServiceRestStub): - def __hash__(self): - return hash("UpdateFeed") - - __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: asset_service.UpdateFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.Feed: - r"""Call the update feed method over HTTP. - - Args: - request (~.asset_service.UpdateFeedRequest): - The request object. Update asset feed request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{feed.name=*/*/feeds/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_update_feed(request, metadata) - pb_request = asset_service.UpdateFeedRequest.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 = asset_service.Feed() - pb_resp = asset_service.Feed.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_feed(resp) - return resp - - class _UpdateSavedQuery(AssetServiceRestStub): - def __hash__(self): - return hash("UpdateSavedQuery") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @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: asset_service.UpdateSavedQueryRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.SavedQuery: - r"""Call the update saved query method over HTTP. - - Args: - request (~.asset_service.UpdateSavedQueryRequest): - The request object. Request to update a saved query. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.SavedQuery: - A saved query which can be shared - with others or used later. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{saved_query.name=*/*/savedQueries/*}', - 'body': 'saved_query', - }, - ] - request, metadata = self._interceptor.pre_update_saved_query(request, metadata) - pb_request = asset_service.UpdateSavedQueryRequest.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 = asset_service.SavedQuery() - pb_resp = asset_service.SavedQuery.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_saved_query(resp) - return resp - - @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - asset_service.AnalyzeIamPolicyResponse]: - # 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._AnalyzeIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_iam_policy_longrunning(self) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], - 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._AnalyzeIamPolicyLongrunning(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_move(self) -> Callable[ - [asset_service.AnalyzeMoveRequest], - asset_service.AnalyzeMoveResponse]: - # 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._AnalyzeMove(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_org_policies(self) -> Callable[ - [asset_service.AnalyzeOrgPoliciesRequest], - asset_service.AnalyzeOrgPoliciesResponse]: - # 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._AnalyzeOrgPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_org_policy_governed_assets(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedAssetsRequest], - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse]: - # 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._AnalyzeOrgPolicyGovernedAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def analyze_org_policy_governed_containers(self) -> Callable[ - [asset_service.AnalyzeOrgPolicyGovernedContainersRequest], - asset_service.AnalyzeOrgPolicyGovernedContainersResponse]: - # 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._AnalyzeOrgPolicyGovernedContainers(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_get_assets_history(self) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - asset_service.BatchGetAssetsHistoryResponse]: - # 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._BatchGetAssetsHistory(self._session, self._host, self._interceptor) # type: ignore - - @property - def batch_get_effective_iam_policies(self) -> Callable[ - [asset_service.BatchGetEffectiveIamPoliciesRequest], - asset_service.BatchGetEffectiveIamPoliciesResponse]: - # 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._BatchGetEffectiveIamPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - asset_service.Feed]: - # 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._CreateFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_saved_query(self) -> Callable[ - [asset_service.CreateSavedQueryRequest], - asset_service.SavedQuery]: - # 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._CreateSavedQuery(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - 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._DeleteFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_saved_query(self) -> Callable[ - [asset_service.DeleteSavedQueryRequest], - 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._DeleteSavedQuery(self._session, self._host, self._interceptor) # type: ignore - - @property - def export_assets(self) -> Callable[ - [asset_service.ExportAssetsRequest], - 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._ExportAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - asset_service.Feed]: - # 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._GetFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_saved_query(self) -> Callable[ - [asset_service.GetSavedQueryRequest], - asset_service.SavedQuery]: - # 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._GetSavedQuery(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - asset_service.ListAssetsResponse]: - # 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._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - asset_service.ListFeedsResponse]: - # 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._ListFeeds(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_saved_queries(self) -> Callable[ - [asset_service.ListSavedQueriesRequest], - asset_service.ListSavedQueriesResponse]: - # 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._ListSavedQueries(self._session, self._host, self._interceptor) # type: ignore - - @property - def query_assets(self) -> Callable[ - [asset_service.QueryAssetsRequest], - asset_service.QueryAssetsResponse]: - # 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._QueryAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - asset_service.SearchAllIamPoliciesResponse]: - # 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._SearchAllIamPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - asset_service.SearchAllResourcesResponse]: - # 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._SearchAllResources(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - asset_service.Feed]: - # 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._UpdateFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_saved_query(self) -> Callable[ - [asset_service.UpdateSavedQueryRequest], - asset_service.SavedQuery]: - # 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._UpdateSavedQuery(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(AssetServiceRestStub): - 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=*/*/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 kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AssetServiceRestTransport', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py b/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py deleted file mode 100644 index 9819b55a..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .asset_service import ( - AnalyzeIamPolicyLongrunningMetadata, - AnalyzeIamPolicyLongrunningRequest, - AnalyzeIamPolicyLongrunningResponse, - AnalyzeIamPolicyRequest, - AnalyzeIamPolicyResponse, - AnalyzeMoveRequest, - AnalyzeMoveResponse, - AnalyzeOrgPoliciesRequest, - AnalyzeOrgPoliciesResponse, - AnalyzeOrgPolicyGovernedAssetsRequest, - AnalyzeOrgPolicyGovernedAssetsResponse, - AnalyzeOrgPolicyGovernedContainersRequest, - AnalyzeOrgPolicyGovernedContainersResponse, - AnalyzerOrgPolicy, - AnalyzerOrgPolicyConstraint, - BatchGetAssetsHistoryRequest, - BatchGetAssetsHistoryResponse, - BatchGetEffectiveIamPoliciesRequest, - BatchGetEffectiveIamPoliciesResponse, - BigQueryDestination, - CreateFeedRequest, - CreateSavedQueryRequest, - DeleteFeedRequest, - DeleteSavedQueryRequest, - ExportAssetsRequest, - ExportAssetsResponse, - Feed, - FeedOutputConfig, - GcsDestination, - GcsOutputResult, - GetFeedRequest, - GetSavedQueryRequest, - IamPolicyAnalysisOutputConfig, - IamPolicyAnalysisQuery, - ListAssetsRequest, - ListAssetsResponse, - ListFeedsRequest, - ListFeedsResponse, - ListSavedQueriesRequest, - ListSavedQueriesResponse, - MoveAnalysis, - MoveAnalysisResult, - MoveImpact, - OutputConfig, - OutputResult, - PartitionSpec, - PubsubDestination, - QueryAssetsOutputConfig, - QueryAssetsRequest, - QueryAssetsResponse, - QueryResult, - SavedQuery, - SearchAllIamPoliciesRequest, - SearchAllIamPoliciesResponse, - SearchAllResourcesRequest, - SearchAllResourcesResponse, - TableFieldSchema, - TableSchema, - UpdateFeedRequest, - UpdateSavedQueryRequest, - ContentType, -) -from .assets import ( - Asset, - AttachedResource, - ConditionEvaluation, - EffectiveTagDetails, - IamPolicyAnalysisResult, - IamPolicyAnalysisState, - IamPolicySearchResult, - RelatedAsset, - RelatedAssets, - RelatedResource, - RelatedResources, - RelationshipAttributes, - Resource, - ResourceSearchResult, - Tag, - TemporalAsset, - TimeWindow, - VersionedResource, -) - -__all__ = ( - 'AnalyzeIamPolicyLongrunningMetadata', - 'AnalyzeIamPolicyLongrunningRequest', - 'AnalyzeIamPolicyLongrunningResponse', - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'AnalyzeMoveRequest', - 'AnalyzeMoveResponse', - 'AnalyzeOrgPoliciesRequest', - 'AnalyzeOrgPoliciesResponse', - 'AnalyzeOrgPolicyGovernedAssetsRequest', - 'AnalyzeOrgPolicyGovernedAssetsResponse', - 'AnalyzeOrgPolicyGovernedContainersRequest', - 'AnalyzeOrgPolicyGovernedContainersResponse', - 'AnalyzerOrgPolicy', - 'AnalyzerOrgPolicyConstraint', - 'BatchGetAssetsHistoryRequest', - 'BatchGetAssetsHistoryResponse', - 'BatchGetEffectiveIamPoliciesRequest', - 'BatchGetEffectiveIamPoliciesResponse', - 'BigQueryDestination', - 'CreateFeedRequest', - 'CreateSavedQueryRequest', - 'DeleteFeedRequest', - 'DeleteSavedQueryRequest', - 'ExportAssetsRequest', - 'ExportAssetsResponse', - 'Feed', - 'FeedOutputConfig', - 'GcsDestination', - 'GcsOutputResult', - 'GetFeedRequest', - 'GetSavedQueryRequest', - 'IamPolicyAnalysisOutputConfig', - 'IamPolicyAnalysisQuery', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'ListSavedQueriesRequest', - 'ListSavedQueriesResponse', - 'MoveAnalysis', - 'MoveAnalysisResult', - 'MoveImpact', - 'OutputConfig', - 'OutputResult', - 'PartitionSpec', - 'PubsubDestination', - 'QueryAssetsOutputConfig', - 'QueryAssetsRequest', - 'QueryAssetsResponse', - 'QueryResult', - 'SavedQuery', - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'TableFieldSchema', - 'TableSchema', - 'UpdateFeedRequest', - 'UpdateSavedQueryRequest', - 'ContentType', - 'Asset', - 'AttachedResource', - 'ConditionEvaluation', - 'EffectiveTagDetails', - 'IamPolicyAnalysisResult', - 'IamPolicyAnalysisState', - 'IamPolicySearchResult', - 'RelatedAsset', - 'RelatedAssets', - 'RelatedResource', - 'RelatedResources', - 'RelationshipAttributes', - 'Resource', - 'ResourceSearchResult', - 'Tag', - 'TemporalAsset', - 'TimeWindow', - 'VersionedResource', -) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py b/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py deleted file mode 100644 index bc8a0318..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py +++ /dev/null @@ -1,4036 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.asset_v1.types import assets as gca_assets -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import expr_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1', - manifest={ - 'ContentType', - 'AnalyzeIamPolicyLongrunningMetadata', - 'ExportAssetsRequest', - 'ExportAssetsResponse', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'BatchGetAssetsHistoryRequest', - 'BatchGetAssetsHistoryResponse', - 'CreateFeedRequest', - 'GetFeedRequest', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'UpdateFeedRequest', - 'DeleteFeedRequest', - 'OutputConfig', - 'OutputResult', - 'GcsOutputResult', - 'GcsDestination', - 'BigQueryDestination', - 'PartitionSpec', - 'PubsubDestination', - 'FeedOutputConfig', - 'Feed', - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - 'IamPolicyAnalysisQuery', - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'IamPolicyAnalysisOutputConfig', - 'AnalyzeIamPolicyLongrunningRequest', - 'AnalyzeIamPolicyLongrunningResponse', - 'SavedQuery', - 'CreateSavedQueryRequest', - 'GetSavedQueryRequest', - 'ListSavedQueriesRequest', - 'ListSavedQueriesResponse', - 'UpdateSavedQueryRequest', - 'DeleteSavedQueryRequest', - 'AnalyzeMoveRequest', - 'AnalyzeMoveResponse', - 'MoveAnalysis', - 'MoveAnalysisResult', - 'MoveImpact', - 'QueryAssetsOutputConfig', - 'QueryAssetsRequest', - 'QueryAssetsResponse', - 'QueryResult', - 'TableSchema', - 'TableFieldSchema', - 'BatchGetEffectiveIamPoliciesRequest', - 'BatchGetEffectiveIamPoliciesResponse', - 'AnalyzerOrgPolicy', - 'AnalyzerOrgPolicyConstraint', - 'AnalyzeOrgPoliciesRequest', - 'AnalyzeOrgPoliciesResponse', - 'AnalyzeOrgPolicyGovernedContainersRequest', - 'AnalyzeOrgPolicyGovernedContainersResponse', - 'AnalyzeOrgPolicyGovernedAssetsRequest', - 'AnalyzeOrgPolicyGovernedAssetsResponse', - }, -) - - -class ContentType(proto.Enum): - r"""Asset content type. - - Values: - CONTENT_TYPE_UNSPECIFIED (0): - Unspecified content type. - RESOURCE (1): - Resource metadata. - IAM_POLICY (2): - The actual IAM policy set on a resource. - ORG_POLICY (4): - The organization policy set on an asset. - ACCESS_POLICY (5): - The Access Context Manager policy set on an - asset. - OS_INVENTORY (6): - The runtime OS Inventory information. - RELATIONSHIP (7): - The related resources. - """ - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - ORG_POLICY = 4 - ACCESS_POLICY = 5 - OS_INVENTORY = 6 - RELATIONSHIP = 7 - - -class AnalyzeIamPolicyLongrunningMetadata(proto.Message): - r"""Represents the metadata of the longrunning operation for the - AnalyzeIamPolicyLongrunning RPC. - - Attributes: - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time the operation was - created. - """ - - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - - -class ExportAssetsRequest(proto.Message): - r"""Export asset request. - - Attributes: - parent (str): - Required. The relative name of the root - asset. This can only be an organization number - (such as "organizations/123"), a project ID - (such as "projects/my-project-id"), or a project - number (such as "projects/12345"), or a folder - number (such as "folders/123"). - read_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp to take an asset snapshot. This can - only be set to a timestamp between the current - time and the current time minus 35 days - (inclusive). If not specified, the current time - will be used. Due to delays in resource data - collection and indexing, there is a volatile - window during which running the same query may - get different results. - asset_types (MutableSequence[str]): - A list of asset types to take a snapshot for. For example: - "compute.googleapis.com/Disk". - - Regular expressions are also supported. For example: - - - "compute.googleapis.com.*" snapshots resources whose - asset type starts with "compute.googleapis.com". - - ".*Instance" snapshots resources whose asset type ends - with "Instance". - - ".*Instance.*" snapshots resources whose asset type - contains "Instance". - - See `RE2 `__ for - all supported regular expression syntax. If the regular - expression does not match any supported asset type, an - INVALID_ARGUMENT error will be returned. - - If specified, only matching assets will be returned, - otherwise, it will snapshot all asset types. See - `Introduction to Cloud Asset - Inventory `__ - for all supported asset types. - content_type (google.cloud.asset_v1.types.ContentType): - Asset content type. If not specified, no - content but the asset name will be returned. - output_config (google.cloud.asset_v1.types.OutputConfig): - Required. Output configuration indicating - where the results will be output to. - relationship_types (MutableSequence[str]): - A list of relationship types to export, for example: - ``INSTANCE_TO_INSTANCEGROUP``. This field should only be - specified if content_type=RELATIONSHIP. - - - If specified: it snapshots specified relationships. It - returns an error if any of the [relationship_types] - doesn't belong to the supported relationship types of the - [asset_types] or if any of the [asset_types] doesn't - belong to the source types of the [relationship_types]. - - Otherwise: it snapshots the supported relationships for - all [asset_types] or returns an error if any of the - [asset_types] has no relationship support. An unspecified - asset types field means all supported asset_types. See - `Introduction to Cloud Asset - Inventory `__ - for all supported asset types and relationship types. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type: 'ContentType' = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='OutputConfig', - ) - relationship_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - - -class ExportAssetsResponse(proto.Message): - r"""The export asset response. This message is returned by the - [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] - method in the returned - [google.longrunning.Operation.response][google.longrunning.Operation.response] - field. - - Attributes: - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time the snapshot was taken. - output_config (google.cloud.asset_v1.types.OutputConfig): - Output configuration indicating where the - results were output to. - output_result (google.cloud.asset_v1.types.OutputResult): - Output result indicating where the assets were exported to. - For example, a set of actual Cloud Storage object URIs where - the assets are exported to. The URIs can be different from - what [output_config] has specified, as the service will - split the output object into multiple ones once it exceeds a - single Cloud Storage object limit. - """ - - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - output_config: 'OutputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='OutputConfig', - ) - output_result: 'OutputResult' = proto.Field( - proto.MESSAGE, - number=3, - message='OutputResult', - ) - - -class ListAssetsRequest(proto.Message): - r"""ListAssets request. - - Attributes: - parent (str): - Required. Name of the organization, folder, or project the - assets belong to. Format: - "organizations/[organization-number]" (such as - "organizations/123"), "projects/[project-id]" (such as - "projects/my-project-id"), "projects/[project-number]" (such - as "projects/12345"), or "folders/[folder-number]" (such as - "folders/12345"). - read_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp to take an asset snapshot. This can - only be set to a timestamp between the current - time and the current time minus 35 days - (inclusive). If not specified, the current time - will be used. Due to delays in resource data - collection and indexing, there is a volatile - window during which running the same query may - get different results. - asset_types (MutableSequence[str]): - A list of asset types to take a snapshot for. For example: - "compute.googleapis.com/Disk". - - Regular expression is also supported. For example: - - - "compute.googleapis.com.*" snapshots resources whose - asset type starts with "compute.googleapis.com". - - ".*Instance" snapshots resources whose asset type ends - with "Instance". - - ".*Instance.*" snapshots resources whose asset type - contains "Instance". - - See `RE2 `__ for - all supported regular expression syntax. If the regular - expression does not match any supported asset type, an - INVALID_ARGUMENT error will be returned. - - If specified, only matching assets will be returned, - otherwise, it will snapshot all asset types. See - `Introduction to Cloud Asset - Inventory `__ - for all supported asset types. - content_type (google.cloud.asset_v1.types.ContentType): - Asset content type. If not specified, no - content but the asset name will be returned. - page_size (int): - The maximum number of assets to be returned - in a single response. Default is 100, minimum is - 1, and maximum is 1000. - page_token (str): - The ``next_page_token`` returned from the previous - ``ListAssetsResponse``, or unspecified for the first - ``ListAssetsRequest``. It is a continuation of a prior - ``ListAssets`` call, and the API should return the next page - of assets. - relationship_types (MutableSequence[str]): - A list of relationship types to output, for example: - ``INSTANCE_TO_INSTANCEGROUP``. This field should only be - specified if content_type=RELATIONSHIP. - - - If specified: it snapshots specified relationships. It - returns an error if any of the [relationship_types] - doesn't belong to the supported relationship types of the - [asset_types] or if any of the [asset_types] doesn't - belong to the source types of the [relationship_types]. - - Otherwise: it snapshots the supported relationships for - all [asset_types] or returns an error if any of the - [asset_types] has no relationship support. An unspecified - asset types field means all supported asset_types. See - `Introduction to Cloud Asset - Inventory `__ - for all supported asset types and relationship types. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type: 'ContentType' = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - page_size: int = proto.Field( - proto.INT32, - number=5, - ) - page_token: str = proto.Field( - proto.STRING, - number=6, - ) - relationship_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - -class ListAssetsResponse(proto.Message): - r"""ListAssets response. - - Attributes: - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time the snapshot was taken. - assets (MutableSequence[google.cloud.asset_v1.types.Asset]): - Assets. - next_page_token (str): - Token to retrieve the next page of results. - It expires 72 hours after the page token for the - first page is generated. Set to empty if there - are no remaining results. - """ - - @property - def raw_page(self): - return self - - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - assets: MutableSequence[gca_assets.Asset] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gca_assets.Asset, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class BatchGetAssetsHistoryRequest(proto.Message): - r"""Batch get assets history request. - - Attributes: - parent (str): - Required. The relative name of the root - asset. It can only be an organization number - (such as "organizations/123"), a project ID - (such as "projects/my-project-id")", or a - project number (such as "projects/12345"). - asset_names (MutableSequence[str]): - A list of the full names of the assets. See: - https://cloud.google.com/asset-inventory/docs/resource-name-format - Example: - - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - - The request becomes a no-op if the asset name list is empty, - and the max size of the asset name list is 100 in one - request. - content_type (google.cloud.asset_v1.types.ContentType): - Optional. The content type. - read_time_window (google.cloud.asset_v1.types.TimeWindow): - Optional. The time window for the asset history. Both - start_time and end_time are optional and if set, it must be - after the current time minus 35 days. If end_time is not - set, it is default to current timestamp. If start_time is - not set, the snapshot of the assets at end_time will be - returned. The returned results contain all temporal assets - whose time window overlap with read_time_window. - relationship_types (MutableSequence[str]): - Optional. A list of relationship types to output, for - example: ``INSTANCE_TO_INSTANCEGROUP``. This field should - only be specified if content_type=RELATIONSHIP. - - - If specified: it outputs specified relationships' history - on the [asset_names]. It returns an error if any of the - [relationship_types] doesn't belong to the supported - relationship types of the [asset_names] or if any of the - [asset_names]'s types doesn't belong to the source types - of the [relationship_types]. - - Otherwise: it outputs the supported relationships' - history on the [asset_names] or returns an error if any - of the [asset_names]'s types has no relationship support. - See `Introduction to Cloud Asset - Inventory `__ - for all supported asset types and relationship types. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - asset_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - content_type: 'ContentType' = proto.Field( - proto.ENUM, - number=3, - enum='ContentType', - ) - read_time_window: gca_assets.TimeWindow = proto.Field( - proto.MESSAGE, - number=4, - message=gca_assets.TimeWindow, - ) - relationship_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - - -class BatchGetAssetsHistoryResponse(proto.Message): - r"""Batch get assets history response. - - Attributes: - assets (MutableSequence[google.cloud.asset_v1.types.TemporalAsset]): - A list of assets with valid time windows. - """ - - assets: MutableSequence[gca_assets.TemporalAsset] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gca_assets.TemporalAsset, - ) - - -class CreateFeedRequest(proto.Message): - r"""Create asset feed request. - - Attributes: - parent (str): - Required. The name of the - project/folder/organization where this feed - should be created in. It can only be an - organization number (such as - "organizations/123"), a folder number (such as - "folders/123"), a project ID (such as - "projects/my-project-id"), or a project number - (such as "projects/12345"). - feed_id (str): - Required. This is the client-assigned asset - feed identifier and it needs to be unique under - a specific parent project/folder/organization. - feed (google.cloud.asset_v1.types.Feed): - Required. The feed details. The field ``name`` must be empty - and it will be generated in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - feed_id: str = proto.Field( - proto.STRING, - number=2, - ) - feed: 'Feed' = proto.Field( - proto.MESSAGE, - number=3, - message='Feed', - ) - - -class GetFeedRequest(proto.Message): - r"""Get asset feed request. - - Attributes: - name (str): - Required. The name of the Feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFeedsRequest(proto.Message): - r"""List asset feeds request. - - Attributes: - parent (str): - Required. The parent - project/folder/organization whose feeds are to - be listed. It can only be using - project/folder/organization number (such as - "folders/12345")", or a project ID (such as - "projects/my-project-id"). - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFeedsResponse(proto.Message): - r""" - - Attributes: - feeds (MutableSequence[google.cloud.asset_v1.types.Feed]): - A list of feeds. - """ - - feeds: MutableSequence['Feed'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Feed', - ) - - -class UpdateFeedRequest(proto.Message): - r"""Update asset feed request. - - Attributes: - feed (google.cloud.asset_v1.types.Feed): - Required. The new values of feed details. It must match an - existing feed and the field ``name`` must be in the format - of: projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Only updates the ``feed`` fields indicated by this - mask. The field mask must not be empty, and it must not - contain fields that are immutable or only set by the server. - """ - - feed: 'Feed' = proto.Field( - proto.MESSAGE, - number=1, - message='Feed', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteFeedRequest(proto.Message): - r""" - - Attributes: - name (str): - Required. The name of the feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OutputConfig(proto.Message): - r"""Output configuration for export assets destination. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.cloud.asset_v1.types.GcsDestination): - Destination on Cloud Storage. - - This field is a member of `oneof`_ ``destination``. - bigquery_destination (google.cloud.asset_v1.types.BigQueryDestination): - Destination on BigQuery. The output table - stores the fields in asset Protobuf as columns - in BigQuery. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_destination: 'GcsDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - bigquery_destination: 'BigQueryDestination' = proto.Field( - proto.MESSAGE, - number=2, - oneof='destination', - message='BigQueryDestination', - ) - - -class OutputResult(proto.Message): - r"""Output result of export assets. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_result (google.cloud.asset_v1.types.GcsOutputResult): - Export result on Cloud Storage. - - This field is a member of `oneof`_ ``result``. - """ - - gcs_result: 'GcsOutputResult' = proto.Field( - proto.MESSAGE, - number=1, - oneof='result', - message='GcsOutputResult', - ) - - -class GcsOutputResult(proto.Message): - r"""A Cloud Storage output result. - - Attributes: - uris (MutableSequence[str]): - List of URIs of the Cloud Storage objects. Example: - "gs://bucket_name/object_name". - """ - - uris: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class GcsDestination(proto.Message): - r"""A Cloud Storage location. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - uri (str): - The URI of the Cloud Storage object. It's the same URI that - is used by gsutil. Example: "gs://bucket_name/object_name". - See `Viewing and Editing Object - Metadata `__ - for more information. - - If the specified Cloud Storage object already exists and - there is no - `hold `__, - it will be overwritten with the exported result. - - This field is a member of `oneof`_ ``object_uri``. - uri_prefix (str): - The URI prefix of all generated Cloud Storage objects. - Example: "gs://bucket_name/object_name_prefix". Each object - URI is in format: "gs://bucket_name/object_name_prefix// and - only contains assets for that type. starts from 0. Example: - "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" - is the first shard of output objects containing all - compute.googleapis.com/Disk assets. An INVALID_ARGUMENT - error will be returned if file with the same name - "gs://bucket_name/object_name_prefix" already exists. - - This field is a member of `oneof`_ ``object_uri``. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='object_uri', - ) - uri_prefix: str = proto.Field( - proto.STRING, - number=2, - oneof='object_uri', - ) - - -class BigQueryDestination(proto.Message): - r"""A BigQuery destination for exporting assets to. - - Attributes: - dataset (str): - Required. The BigQuery dataset in format - "projects/projectId/datasets/datasetId", to which the - snapshot result should be exported. If this dataset does not - exist, the export call returns an INVALID_ARGUMENT error. - Setting the ``contentType`` for ``exportAssets`` determines - the - `schema `__ - of the BigQuery table. Setting - ``separateTablesPerAssetType`` to ``TRUE`` also influences - the schema. - table (str): - Required. The BigQuery table to which the - snapshot result should be written. If this table - does not exist, a new table with the given name - will be created. - force (bool): - If the destination table already exists and this flag is - ``TRUE``, the table will be overwritten by the contents of - assets snapshot. If the flag is ``FALSE`` or unset and the - destination table already exists, the export call returns an - INVALID_ARGUMEMT error. - partition_spec (google.cloud.asset_v1.types.PartitionSpec): - [partition_spec] determines whether to export to partitioned - table(s) and how to partition the data. - - If [partition_spec] is unset or - [partition_spec.partition_key] is unset or - ``PARTITION_KEY_UNSPECIFIED``, the snapshot results will be - exported to non-partitioned table(s). [force] will decide - whether to overwrite existing table(s). - - If [partition_spec] is specified. First, the snapshot - results will be written to partitioned table(s) with two - additional timestamp columns, readTime and requestTime, one - of which will be the partition key. Secondly, in the case - when any destination table already exists, it will first try - to update existing table's schema as necessary by appending - additional columns. Then, if [force] is ``TRUE``, the - corresponding partition will be overwritten by the snapshot - results (data in different partitions will remain intact); - if [force] is unset or ``FALSE``, it will append the data. - An error will be returned if the schema update or data - appension fails. - separate_tables_per_asset_type (bool): - If this flag is ``TRUE``, the snapshot results will be - written to one or multiple tables, each of which contains - results of one asset type. The [force] and [partition_spec] - fields will apply to each of them. - - Field [table] will be concatenated with "*" and the asset - type names (see - https://cloud.google.com/asset-inventory/docs/supported-asset-types - for supported asset types) to construct per-asset-type table - names, in which all non-alphanumeric characters like "." and - "/" will be substituted by "*". Example: if field [table] is - "mytable" and snapshot results contain - "storage.googleapis.com/Bucket" assets, the corresponding - table name will be "mytable_storage_googleapis_com_Bucket". - If any of these tables does not exist, a new table with the - concatenated name will be created. - - When [content_type] in the ExportAssetsRequest is - ``RESOURCE``, the schema of each table will include - RECORD-type columns mapped to the nested fields in the - Asset.resource.data field of that asset type (up to the 15 - nested level BigQuery supports - (https://cloud.google.com/bigquery/docs/nested-repeated#limitations)). - The fields in >15 nested levels will be stored in JSON - format string as a child column of its parent RECORD column. - - If error occurs when exporting to any table, the whole - export call will return an error but the export results that - already succeed will persist. Example: if exporting to - table_type_A succeeds when exporting to table_type_B fails - during one export call, the results in table_type_A will - persist and there will not be partial results persisting in - a table. - """ - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - table: str = proto.Field( - proto.STRING, - number=2, - ) - force: bool = proto.Field( - proto.BOOL, - number=3, - ) - partition_spec: 'PartitionSpec' = proto.Field( - proto.MESSAGE, - number=4, - message='PartitionSpec', - ) - separate_tables_per_asset_type: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class PartitionSpec(proto.Message): - r"""Specifications of BigQuery partitioned table as export - destination. - - Attributes: - partition_key (google.cloud.asset_v1.types.PartitionSpec.PartitionKey): - The partition key for BigQuery partitioned - table. - """ - class PartitionKey(proto.Enum): - r"""This enum is used to determine the partition key column when - exporting assets to BigQuery partitioned table(s). Note that, if the - partition key is a timestamp column, the actual partition is based - on its date value (expressed in UTC. see details in - https://cloud.google.com/bigquery/docs/partitioned-tables#date_timestamp_partitioned_tables). - - Values: - PARTITION_KEY_UNSPECIFIED (0): - Unspecified partition key. If used, it means - using non-partitioned table. - READ_TIME (1): - The time when the snapshot is taken. If specified as - partition key, the result table(s) is partitoned by the - additional timestamp column, readTime. If [read_time] in - ExportAssetsRequest is specified, the readTime column's - value will be the same as it. Otherwise, its value will be - the current time that is used to take the snapshot. - REQUEST_TIME (2): - The time when the request is received and - started to be processed. If specified as - partition key, the result table(s) is partitoned - by the requestTime column, an additional - timestamp column representing when the request - was received. - """ - PARTITION_KEY_UNSPECIFIED = 0 - READ_TIME = 1 - REQUEST_TIME = 2 - - partition_key: PartitionKey = proto.Field( - proto.ENUM, - number=1, - enum=PartitionKey, - ) - - -class PubsubDestination(proto.Message): - r"""A Pub/Sub destination. - - Attributes: - topic (str): - The name of the Pub/Sub topic to publish to. Example: - ``projects/PROJECT_ID/topics/TOPIC_ID``. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FeedOutputConfig(proto.Message): - r"""Output configuration for asset feed destination. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - pubsub_destination (google.cloud.asset_v1.types.PubsubDestination): - Destination on Pub/Sub. - - This field is a member of `oneof`_ ``destination``. - """ - - pubsub_destination: 'PubsubDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='PubsubDestination', - ) - - -class Feed(proto.Message): - r"""An asset feed used to export asset updates to a destinations. - An asset feed filter controls what updates are exported. The - asset feed must be created within a project, organization, or - folder. Supported destinations are: - - Pub/Sub topics. - - Attributes: - name (str): - Required. The format will be - projects/{project_number}/feeds/{client-assigned_feed_identifier} - or - folders/{folder_number}/feeds/{client-assigned_feed_identifier} - or - organizations/{organization_number}/feeds/{client-assigned_feed_identifier} - - The client-assigned feed identifier must be unique within - the parent project/folder/organization. - asset_names (MutableSequence[str]): - A list of the full names of the assets to receive updates. - You must specify either or both of asset_names and - asset_types. Only asset updates matching specified - asset_names or asset_types are exported to the feed. - Example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - For a list of the full names for supported asset types, see - `Resource name - format `__. - asset_types (MutableSequence[str]): - A list of types of the assets to receive updates. You must - specify either or both of asset_names and asset_types. Only - asset updates matching specified asset_names or asset_types - are exported to the feed. Example: - ``"compute.googleapis.com/Disk"`` - - For a list of all supported asset types, see `Supported - asset - types `__. - content_type (google.cloud.asset_v1.types.ContentType): - Asset content type. If not specified, no - content but the asset name and type will be - returned. - feed_output_config (google.cloud.asset_v1.types.FeedOutputConfig): - Required. Feed output configuration defining - where the asset updates are published to. - condition (google.type.expr_pb2.Expr): - A condition which determines whether an asset update should - be published. If specified, an asset will be returned only - when the expression evaluates to true. When set, - ``expression`` field in the ``Expr`` must be a valid [CEL - expression] (https://github.com/google/cel-spec) on a - TemporalAsset with name ``temporal_asset``. Example: a Feed - with expression ("temporal_asset.deleted == true") will only - publish Asset deletions. Other fields of ``Expr`` are - optional. - - See our `user - guide `__ - for detailed instructions. - relationship_types (MutableSequence[str]): - A list of relationship types to output, for example: - ``INSTANCE_TO_INSTANCEGROUP``. This field should only be - specified if content_type=RELATIONSHIP. - - - If specified: it outputs specified relationship updates - on the [asset_names] or the [asset_types]. It returns an - error if any of the [relationship_types] doesn't belong - to the supported relationship types of the [asset_names] - or [asset_types], or any of the [asset_names] or the - [asset_types] doesn't belong to the source types of the - [relationship_types]. - - Otherwise: it outputs the supported relationships of the - types of [asset_names] and [asset_types] or returns an - error if any of the [asset_names] or the [asset_types] - has no replationship support. See `Introduction to Cloud - Asset - Inventory `__ - for all supported asset types and relationship types. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - asset_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type: 'ContentType' = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - feed_output_config: 'FeedOutputConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='FeedOutputConfig', - ) - condition: expr_pb2.Expr = proto.Field( - proto.MESSAGE, - number=6, - message=expr_pb2.Expr, - ) - relationship_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=7, - ) - - -class SearchAllResourcesRequest(proto.Message): - r"""Search all resources request. - - Attributes: - scope (str): - Required. A scope can be a project, a folder, or an - organization. The search is limited to the resources within - the ``scope``. The caller must be granted the - ```cloudasset.assets.searchAllResources`` `__ - permission on the desired scope. - - The allowed values are: - - - projects/{PROJECT_ID} (e.g., "projects/foo-bar") - - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") - - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - query (str): - Optional. The query statement. See `how to construct a - query `__ - for more information. If not specified or empty, it will - search all the resources within the specified ``scope``. - - Examples: - - - ``name:Important`` to find Google Cloud resources whose - name contains ``Important`` as a word. - - ``name=Important`` to find the Google Cloud resource - whose name is exactly ``Important``. - - ``displayName:Impor*`` to find Google Cloud resources - whose display name contains ``Impor`` as a prefix of any - word in the field. - - ``location:us-west*`` to find Google Cloud resources - whose location contains both ``us`` and ``west`` as - prefixes. - - ``labels:prod`` to find Google Cloud resources whose - labels contain ``prod`` as a key or value. - - ``labels.env:prod`` to find Google Cloud resources that - have a label ``env`` and its value is ``prod``. - - ``labels.env:*`` to find Google Cloud resources that have - a label ``env``. - - ``tagKeys:env`` to find Google Cloud resources that have - directly attached tags where the - ```TagKey`` `__ - .\ ``namespacedName`` contains ``env``. - - ``tagValues:prod*`` to find Google Cloud resources that - have directly attached tags where the - ```TagValue`` `__ - .\ ``namespacedName`` contains a word prefixed by - ``prod``. - - ``tagValueIds=tagValues/123`` to find Google Cloud - resources that have directly attached tags where the - ```TagValue`` `__ - .\ ``name`` is exactly ``tagValues/123``. - - ``effectiveTagKeys:env`` to find Google Cloud resources - that have directly attached or inherited tags where the - ```TagKey`` `__ - .\ ``namespacedName`` contains ``env``. - - ``effectiveTagValues:prod*`` to find Google Cloud - resources that have directly attached or inherited tags - where the - ```TagValue`` `__ - .\ ``namespacedName`` contains a word prefixed by - ``prod``. - - ``effectiveTagValueIds=tagValues/123`` to find Google - Cloud resources that have directly attached or inherited - tags where the - ```TagValue`` `__ - .\ ``name`` is exactly ``tagValues/123``. - - ``kmsKey:key`` to find Google Cloud resources encrypted - with a customer-managed encryption key whose name - contains ``key`` as a word. This field is deprecated. - Please use the ``kmsKeys`` field to retrieve Cloud KMS - key information. - - ``kmsKeys:key`` to find Google Cloud resources encrypted - with customer-managed encryption keys whose name contains - the word ``key``. - - ``relationships:instance-group-1`` to find Google Cloud - resources that have relationships with - ``instance-group-1`` in the related resource name. - - ``relationships:INSTANCE_TO_INSTANCEGROUP`` to find - Compute Engine instances that have relationships of type - ``INSTANCE_TO_INSTANCEGROUP``. - - ``relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1`` - to find Compute Engine instances that have relationships - with ``instance-group-1`` in the Compute Engine instance - group resource name, for relationship type - ``INSTANCE_TO_INSTANCEGROUP``. - - ``state:ACTIVE`` to find Google Cloud resources whose - state contains ``ACTIVE`` as a word. - - ``NOT state:ACTIVE`` to find Google Cloud resources whose - state doesn't contain ``ACTIVE`` as a word. - - ``createTime<1609459200`` to find Google Cloud resources - that were created before ``2021-01-01 00:00:00 UTC``. - ``1609459200`` is the epoch timestamp of - ``2021-01-01 00:00:00 UTC`` in seconds. - - ``updateTime>1609459200`` to find Google Cloud resources - that were updated after ``2021-01-01 00:00:00 UTC``. - ``1609459200`` is the epoch timestamp of - ``2021-01-01 00:00:00 UTC`` in seconds. - - ``Important`` to find Google Cloud resources that contain - ``Important`` as a word in any of the searchable fields. - - ``Impor*`` to find Google Cloud resources that contain - ``Impor`` as a prefix of any word in any of the - searchable fields. - - ``Important location:(us-west1 OR global)`` to find - Google Cloud resources that contain ``Important`` as a - word in any of the searchable fields and are also located - in the ``us-west1`` region or the ``global`` location. - asset_types (MutableSequence[str]): - Optional. A list of asset types that this request searches - for. If empty, it will search all the `searchable asset - types `__. - - Regular expressions are also supported. For example: - - - "compute.googleapis.com.*" snapshots resources whose - asset type starts with "compute.googleapis.com". - - ".*Instance" snapshots resources whose asset type ends - with "Instance". - - ".*Instance.*" snapshots resources whose asset type - contains "Instance". - - See `RE2 `__ for - all supported regular expression syntax. If the regular - expression does not match any supported asset type, an - INVALID_ARGUMENT error will be returned. - page_size (int): - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If - set to zero or a negative value, server will pick an - appropriate default. Returned results may be fewer than - requested. When this happens, there could be more results as - long as ``next_page_token`` is returned. - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``page_token`` must be the value of ``next_page_token`` from - the previous response. The values of all other method - parameters, must be identical to those in the previous call. - order_by (str): - Optional. A comma-separated list of fields specifying the - sorting order of the results. The default order is - ascending. Add " DESC" after the field name to indicate - descending order. Redundant space characters are ignored. - Example: "location DESC, name". Only the following fields in - the response are sortable: - - - name - - assetType - - project - - displayName - - description - - location - - createTime - - updateTime - - state - - parentFullResourceName - - parentAssetType - read_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. A comma-separated list of fields that you want - returned in the results. The following fields are returned - by default if not specified: - - - ``name`` - - ``assetType`` - - ``project`` - - ``folders`` - - ``organization`` - - ``displayName`` - - ``description`` - - ``location`` - - ``labels`` - - ``tags`` - - ``effectiveTags`` - - ``networkTags`` - - ``kmsKeys`` - - ``createTime`` - - ``updateTime`` - - ``state`` - - ``additionalAttributes`` - - ``parentFullResourceName`` - - ``parentAssetType`` - - Some fields of large size, such as ``versionedResources``, - ``attachedResources``, ``effectiveTags`` etc., are not - returned by default, but you can specify them in the - ``read_mask`` parameter if you want to include them. If - ``"*"`` is specified, all `available - fields `__ - are returned. Examples: ``"name,location"``, - ``"name,versionedResources"``, ``"*"``. Any invalid field - path will trigger INVALID_ARGUMENT error. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - order_by: str = proto.Field( - proto.STRING, - number=6, - ) - read_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=8, - message=field_mask_pb2.FieldMask, - ) - - -class SearchAllResourcesResponse(proto.Message): - r"""Search all resources response. - - Attributes: - results (MutableSequence[google.cloud.asset_v1.types.ResourceSearchResult]): - A list of Resources that match the search - query. It contains the resource standard - metadata information. - next_page_token (str): - If there are more results than those appearing in this - response, then ``next_page_token`` is included. To get the - next set of results, call this method again using the value - of ``next_page_token`` as ``page_token``. - """ - - @property - def raw_page(self): - return self - - results: MutableSequence[gca_assets.ResourceSearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gca_assets.ResourceSearchResult, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SearchAllIamPoliciesRequest(proto.Message): - r"""Search all IAM policies request. - - Attributes: - scope (str): - Required. A scope can be a project, a folder, or an - organization. The search is limited to the IAM policies - within the ``scope``. The caller must be granted the - ```cloudasset.assets.searchAllIamPolicies`` `__ - permission on the desired scope. - - The allowed values are: - - - projects/{PROJECT_ID} (e.g., "projects/foo-bar") - - projects/{PROJECT_NUMBER} (e.g., "projects/12345678") - - folders/{FOLDER_NUMBER} (e.g., "folders/1234567") - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - query (str): - Optional. The query statement. See `how to construct a - query `__ - for more information. If not specified or empty, it will - search all the IAM policies within the specified ``scope``. - Note that the query string is compared against each IAM - policy binding, including its principals, roles, and IAM - conditions. The returned IAM policies will only contain the - bindings that match your query. To learn more about the IAM - policy structure, see the `IAM policy - documentation `__. - - Examples: - - - ``policy:amy@gmail.com`` to find IAM policy bindings that - specify user "amy@gmail.com". - - ``policy:roles/compute.admin`` to find IAM policy - bindings that specify the Compute Admin role. - - ``policy:comp*`` to find IAM policy bindings that contain - "comp" as a prefix of any word in the binding. - - ``policy.role.permissions:storage.buckets.update`` to - find IAM policy bindings that specify a role containing - "storage.buckets.update" permission. Note that if callers - don't have ``iam.roles.get`` access to a role's included - permissions, policy bindings that specify this role will - be dropped from the search results. - - ``policy.role.permissions:upd*`` to find IAM policy - bindings that specify a role containing "upd" as a prefix - of any word in the role permission. Note that if callers - don't have ``iam.roles.get`` access to a role's included - permissions, policy bindings that specify this role will - be dropped from the search results. - - ``resource:organizations/123456`` to find IAM policy - bindings that are set on "organizations/123456". - - ``resource=//cloudresourcemanager.googleapis.com/projects/myproject`` - to find IAM policy bindings that are set on the project - named "myproject". - - ``Important`` to find IAM policy bindings that contain - "Important" as a word in any of the searchable fields - (except for the included permissions). - - ``resource:(instance1 OR instance2) policy:amy`` to find - IAM policy bindings that are set on resources "instance1" - or "instance2" and also specify user "amy". - - ``roles:roles/compute.admin`` to find IAM policy bindings - that specify the Compute Admin role. - - ``memberTypes:user`` to find IAM policy bindings that - contain the principal type "user". - page_size (int): - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If - set to zero or a negative value, server will pick an - appropriate default. Returned results may be fewer than - requested. When this happens, there could be more results as - long as ``next_page_token`` is returned. - page_token (str): - Optional. If present, retrieve the next batch of results - from the preceding call to this method. ``page_token`` must - be the value of ``next_page_token`` from the previous - response. The values of all other method parameters must be - identical to those in the previous call. - asset_types (MutableSequence[str]): - Optional. A list of asset types that the IAM policies are - attached to. If empty, it will search the IAM policies that - are attached to all the `searchable asset - types `__. - - Regular expressions are also supported. For example: - - - "compute.googleapis.com.*" snapshots IAM policies - attached to asset type starts with - "compute.googleapis.com". - - ".*Instance" snapshots IAM policies attached to asset - type ends with "Instance". - - ".*Instance.*" snapshots IAM policies attached to asset - type contains "Instance". - - See `RE2 `__ for - all supported regular expression syntax. If the regular - expression does not match any supported asset type, an - INVALID_ARGUMENT error will be returned. - order_by (str): - Optional. A comma-separated list of fields specifying the - sorting order of the results. The default order is - ascending. Add " DESC" after the field name to indicate - descending order. Redundant space characters are ignored. - Example: "assetType DESC, resource". Only singular primitive - fields in the response are sortable: - - - resource - - assetType - - project All the other fields such as repeated fields - (e.g., ``folders``) and non-primitive fields (e.g., - ``policy``) are not supported. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - order_by: str = proto.Field( - proto.STRING, - number=7, - ) - - -class SearchAllIamPoliciesResponse(proto.Message): - r"""Search all IAM policies response. - - Attributes: - results (MutableSequence[google.cloud.asset_v1.types.IamPolicySearchResult]): - A list of IAM policies that match the search - query. Related information such as the - associated resource is returned along with the - policy. - next_page_token (str): - Set if there are more results than those appearing in this - response; to get the next set of results, call this method - again, using this value as the ``page_token``. - """ - - @property - def raw_page(self): - return self - - results: MutableSequence[gca_assets.IamPolicySearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gca_assets.IamPolicySearchResult, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class IamPolicyAnalysisQuery(proto.Message): - r"""IAM policy analysis query message. - - Attributes: - scope (str): - Required. The relative name of the root asset. Only - resources and IAM policies within the scope will be - analyzed. - - This can only be an organization number (such as - "organizations/123"), a folder number (such as - "folders/123"), a project ID (such as - "projects/my-project-id"), or a project number (such as - "projects/12345"). - - To know how to get organization id, visit - `here `__. - - To know how to get folder or project id, visit - `here `__. - resource_selector (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.ResourceSelector): - Optional. Specifies a resource for analysis. - identity_selector (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.IdentitySelector): - Optional. Specifies an identity for analysis. - access_selector (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.AccessSelector): - Optional. Specifies roles or permissions for - analysis. This is optional. - options (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.Options): - Optional. The query options. - condition_context (google.cloud.asset_v1.types.IamPolicyAnalysisQuery.ConditionContext): - Optional. The hypothetical context for IAM - conditions evaluation. - """ - - class ResourceSelector(proto.Message): - r"""Specifies the resource to analyze for access policies, which - may be set directly on the resource, or on ancestors such as - organizations, folders or projects. - - Attributes: - full_resource_name (str): - Required. The [full resource name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of a resource of `supported resource - types `__. - """ - - full_resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - - class IdentitySelector(proto.Message): - r"""Specifies an identity for which to determine resource access, - based on roles assigned either directly to them or to the groups - they belong to, directly or indirectly. - - Attributes: - identity (str): - Required. The identity appear in the form of principals in - `IAM policy - binding `__. - - The examples of supported forms are: - "user:mike@example.com", "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com". - - Notice that wildcard characters (such as \* and ?) are not - supported. You must give a specific identity. - """ - - identity: str = proto.Field( - proto.STRING, - number=1, - ) - - class AccessSelector(proto.Message): - r"""Specifies roles and/or permissions to analyze, to determine - both the identities possessing them and the resources they - control. If multiple values are specified, results will include - roles or permissions matching any of them. The total number of - roles and permissions should be equal or less than 10. - - Attributes: - roles (MutableSequence[str]): - Optional. The roles to appear in result. - permissions (MutableSequence[str]): - Optional. The permissions to appear in - result. - """ - - roles: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - permissions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - class Options(proto.Message): - r"""Contains query options. - - Attributes: - expand_groups (bool): - Optional. If true, the identities section of the result will - expand any Google groups appearing in an IAM policy binding. - - If - [IamPolicyAnalysisQuery.identity_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.identity_selector] - is specified, the identity in the result will be determined - by the selector, and this flag is not allowed to set. - - If true, the default max expansion per group is 1000 for - AssetService.AnalyzeIamPolicy][]. - - Default is false. - expand_roles (bool): - Optional. If true, the access section of result will expand - any roles appearing in IAM policy bindings to include their - permissions. - - If - [IamPolicyAnalysisQuery.access_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.access_selector] - is specified, the access section of the result will be - determined by the selector, and this flag is not allowed to - set. - - Default is false. - expand_resources (bool): - Optional. If true and - [IamPolicyAnalysisQuery.resource_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.resource_selector] - is not specified, the resource section of the result will - expand any resource attached to an IAM policy to include - resources lower in the resource hierarchy. - - For example, if the request analyzes for which resources - user A has permission P, and the results include an IAM - policy with P on a Google Cloud folder, the results will - also include resources in that folder with permission P. - - If true and - [IamPolicyAnalysisQuery.resource_selector][google.cloud.asset.v1.IamPolicyAnalysisQuery.resource_selector] - is specified, the resource section of the result will expand - the specified resource to include resources lower in the - resource hierarchy. Only project or lower resources are - supported. Folder and organization resources cannot be used - together with this option. - - For example, if the request analyzes for which users have - permission P on a Google Cloud project with this option - enabled, the results will include all users who have - permission P on that project or any lower resource. - - If true, the default max expansion per resource is 1000 for - AssetService.AnalyzeIamPolicy][] and 100000 for - AssetService.AnalyzeIamPolicyLongrunning][]. - - Default is false. - output_resource_edges (bool): - Optional. If true, the result will output the - relevant parent/child relationships between - resources. Default is false. - output_group_edges (bool): - Optional. If true, the result will output the - relevant membership relationships between groups - and other groups, and between groups and - principals. Default is false. - analyze_service_account_impersonation (bool): - Optional. If true, the response will include access analysis - from identities to resources via service account - impersonation. This is a very expensive operation, because - many derived queries will be executed. We highly recommend - you use - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning] - RPC instead. - - For example, if the request analyzes for which resources - user A has permission P, and there's an IAM policy states - user A has iam.serviceAccounts.getAccessToken permission to - a service account SA, and there's another IAM policy states - service account SA has permission P to a Google Cloud folder - F, then user A potentially has access to the Google Cloud - folder F. And those advanced analysis results will be - included in - [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. - - Another example, if the request analyzes for who has - permission P to a Google Cloud folder F, and there's an IAM - policy states user A has iam.serviceAccounts.actAs - permission to a service account SA, and there's another IAM - policy states service account SA has permission P to the - Google Cloud folder F, then user A potentially has access to - the Google Cloud folder F. And those advanced analysis - results will be included in - [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. - - Only the following permissions are considered in this - analysis: - - - ``iam.serviceAccounts.actAs`` - - ``iam.serviceAccounts.signBlob`` - - ``iam.serviceAccounts.signJwt`` - - ``iam.serviceAccounts.getAccessToken`` - - ``iam.serviceAccounts.getOpenIdToken`` - - ``iam.serviceAccounts.implicitDelegation`` - - Default is false. - """ - - expand_groups: bool = proto.Field( - proto.BOOL, - number=1, - ) - expand_roles: bool = proto.Field( - proto.BOOL, - number=2, - ) - expand_resources: bool = proto.Field( - proto.BOOL, - number=3, - ) - output_resource_edges: bool = proto.Field( - proto.BOOL, - number=4, - ) - output_group_edges: bool = proto.Field( - proto.BOOL, - number=5, - ) - analyze_service_account_impersonation: bool = proto.Field( - proto.BOOL, - number=6, - ) - - class ConditionContext(proto.Message): - r"""The IAM conditions context. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - access_time (google.protobuf.timestamp_pb2.Timestamp): - The hypothetical access timestamp to evaluate IAM - conditions. Note that this value must not be earlier than - the current time; otherwise, an INVALID_ARGUMENT error will - be returned. - - This field is a member of `oneof`_ ``TimeContext``. - """ - - access_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - oneof='TimeContext', - message=timestamp_pb2.Timestamp, - ) - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - resource_selector: ResourceSelector = proto.Field( - proto.MESSAGE, - number=2, - message=ResourceSelector, - ) - identity_selector: IdentitySelector = proto.Field( - proto.MESSAGE, - number=3, - message=IdentitySelector, - ) - access_selector: AccessSelector = proto.Field( - proto.MESSAGE, - number=4, - message=AccessSelector, - ) - options: Options = proto.Field( - proto.MESSAGE, - number=5, - message=Options, - ) - condition_context: ConditionContext = proto.Field( - proto.MESSAGE, - number=6, - message=ConditionContext, - ) - - -class AnalyzeIamPolicyRequest(proto.Message): - r"""A request message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - - Attributes: - analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): - Required. The request query. - saved_analysis_query (str): - Optional. The name of a saved query, which must be in the - format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - If both ``analysis_query`` and ``saved_analysis_query`` are - provided, they will be merged together with the - ``saved_analysis_query`` as base and the ``analysis_query`` - as overrides. For more details of the merge behavior, please - refer to the - `MergeFrom `__ - page. - - Note that you cannot override primitive fields with default - value, such as 0 or empty string, etc., because we use - proto3, which doesn't support field presence yet. - execution_timeout (google.protobuf.duration_pb2.Duration): - Optional. Amount of time executable has to complete. See - JSON representation of - `Duration `__. - - If this field is set with a value less than the RPC - deadline, and the execution of your query hasn't finished in - the specified execution timeout, you will get a response - with partial result. Otherwise, your query's execution will - continue until the RPC deadline. If it's not finished until - then, you will get a DEADLINE_EXCEEDED error. - - Default is empty. - """ - - analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - saved_analysis_query: str = proto.Field( - proto.STRING, - number=3, - ) - execution_timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=2, - message=duration_pb2.Duration, - ) - - -class AnalyzeIamPolicyResponse(proto.Message): - r"""A response message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - - Attributes: - main_analysis (google.cloud.asset_v1.types.AnalyzeIamPolicyResponse.IamPolicyAnalysis): - The main analysis that matches the original - request. - service_account_impersonation_analysis (MutableSequence[google.cloud.asset_v1.types.AnalyzeIamPolicyResponse.IamPolicyAnalysis]): - The service account impersonation analysis if - [AnalyzeIamPolicyRequest.analyze_service_account_impersonation][] - is enabled. - fully_explored (bool): - Represents whether all entries in the - [main_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.main_analysis] - and - [service_account_impersonation_analysis][google.cloud.asset.v1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis] - have been fully explored to answer the query in the request. - """ - - class IamPolicyAnalysis(proto.Message): - r"""An analysis message to group the query and results. - - Attributes: - analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): - The analysis query. - analysis_results (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult]): - A list of - [IamPolicyAnalysisResult][google.cloud.asset.v1.IamPolicyAnalysisResult] - that matches the analysis query, or empty if no result is - found. - fully_explored (bool): - Represents whether all entries in the - [analysis_results][google.cloud.asset.v1.AnalyzeIamPolicyResponse.IamPolicyAnalysis.analysis_results] - have been fully explored to answer the query. - non_critical_errors (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisState]): - A list of non-critical errors happened during - the query handling. - """ - - analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - analysis_results: MutableSequence[gca_assets.IamPolicyAnalysisResult] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gca_assets.IamPolicyAnalysisResult, - ) - fully_explored: bool = proto.Field( - proto.BOOL, - number=3, - ) - non_critical_errors: MutableSequence[gca_assets.IamPolicyAnalysisState] = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gca_assets.IamPolicyAnalysisState, - ) - - main_analysis: IamPolicyAnalysis = proto.Field( - proto.MESSAGE, - number=1, - message=IamPolicyAnalysis, - ) - service_account_impersonation_analysis: MutableSequence[IamPolicyAnalysis] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=IamPolicyAnalysis, - ) - fully_explored: bool = proto.Field( - proto.BOOL, - number=3, - ) - - -class IamPolicyAnalysisOutputConfig(proto.Message): - r"""Output configuration for export IAM policy analysis - destination. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.GcsDestination): - Destination on Cloud Storage. - - This field is a member of `oneof`_ ``destination``. - bigquery_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.BigQueryDestination): - Destination on BigQuery. - - This field is a member of `oneof`_ ``destination``. - """ - - class GcsDestination(proto.Message): - r"""A Cloud Storage location. - - Attributes: - uri (str): - Required. The URI of the Cloud Storage object. It's the same - URI that is used by gsutil. Example: - "gs://bucket_name/object_name". See `Viewing and Editing - Object - Metadata `__ - for more information. - - If the specified Cloud Storage object already exists and - there is no - `hold `__, - it will be overwritten with the analysis result. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - ) - - class BigQueryDestination(proto.Message): - r"""A BigQuery destination. - - Attributes: - dataset (str): - Required. The BigQuery dataset in format - "projects/projectId/datasets/datasetId", to which the - analysis results should be exported. If this dataset does - not exist, the export call will return an INVALID_ARGUMENT - error. - table_prefix (str): - Required. The prefix of the BigQuery tables to which the - analysis results will be written. Tables will be created - based on this table_prefix if not exist: - - - _analysis table will contain export - operation's metadata. - - _analysis_result will contain all the - [IamPolicyAnalysisResult][google.cloud.asset.v1.IamPolicyAnalysisResult]. - When [partition_key] is specified, both tables will be - partitioned based on the [partition_key]. - partition_key (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey): - The partition key for BigQuery partitioned - table. - write_disposition (str): - Optional. Specifies the action that occurs if the - destination table or partition already exists. The following - values are supported: - - - WRITE_TRUNCATE: If the table or partition already exists, - BigQuery overwrites the entire table or all the - partitions data. - - WRITE_APPEND: If the table or partition already exists, - BigQuery appends the data to the table or the latest - partition. - - WRITE_EMPTY: If the table already exists and contains - data, an error is returned. - - The default value is WRITE_APPEND. Each action is atomic and - only occurs if BigQuery is able to complete the job - successfully. Details are at - https://cloud.google.com/bigquery/docs/loading-data-local#appending_to_or_overwriting_a_table_using_a_local_file. - """ - class PartitionKey(proto.Enum): - r"""This enum determines the partition key column for the - bigquery tables. Partitioning can improve query performance and - reduce query cost by filtering partitions. Refer to - https://cloud.google.com/bigquery/docs/partitioned-tables for - details. - - Values: - PARTITION_KEY_UNSPECIFIED (0): - Unspecified partition key. Tables won't be - partitioned using this option. - REQUEST_TIME (1): - The time when the request is received. If - specified as partition key, the result table(s) - is partitoned by the RequestTime column, an - additional timestamp column representing when - the request was received. - """ - PARTITION_KEY_UNSPECIFIED = 0 - REQUEST_TIME = 1 - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - table_prefix: str = proto.Field( - proto.STRING, - number=2, - ) - partition_key: 'IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey' = proto.Field( - proto.ENUM, - number=3, - enum='IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey', - ) - write_disposition: str = proto.Field( - proto.STRING, - number=4, - ) - - gcs_destination: GcsDestination = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message=GcsDestination, - ) - bigquery_destination: BigQueryDestination = proto.Field( - proto.MESSAGE, - number=2, - oneof='destination', - message=BigQueryDestination, - ) - - -class AnalyzeIamPolicyLongrunningRequest(proto.Message): - r"""A request message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - - Attributes: - analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): - Required. The request query. - saved_analysis_query (str): - Optional. The name of a saved query, which must be in the - format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - - If both ``analysis_query`` and ``saved_analysis_query`` are - provided, they will be merged together with the - ``saved_analysis_query`` as base and the ``analysis_query`` - as overrides. For more details of the merge behavior, please - refer to the - `MergeFrom `__ - doc. - - Note that you cannot override primitive fields with default - value, such as 0 or empty string, etc., because we use - proto3, which doesn't support field presence yet. - output_config (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig): - Required. Output configuration indicating - where the results will be output to. - """ - - analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - saved_analysis_query: str = proto.Field( - proto.STRING, - number=3, - ) - output_config: 'IamPolicyAnalysisOutputConfig' = proto.Field( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisOutputConfig', - ) - - -class AnalyzeIamPolicyLongrunningResponse(proto.Message): - r"""A response message for - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - - """ - - -class SavedQuery(proto.Message): - r"""A saved query which can be shared with others or used later. - - Attributes: - name (str): - The resource name of the saved query. The format must be: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - description (str): - The description of this saved query. This - value should be fewer than 255 characters. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The create time of this saved - query. - creator (str): - Output only. The account's email address who - has created this saved query. - last_update_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The last update time of this - saved query. - last_updater (str): - Output only. The account's email address who - has updated this saved query most recently. - labels (MutableMapping[str, str]): - Labels applied on the resource. - This value should not contain more than 10 - entries. The key and value of each entry must be - non-empty and fewer than 64 characters. - content (google.cloud.asset_v1.types.SavedQuery.QueryContent): - The query content. - """ - - class QueryContent(proto.Message): - r"""The query content. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - iam_policy_analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): - An IAM Policy Analysis query, which could be used in the - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy] - RPC or the - [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning] - RPC. - - This field is a member of `oneof`_ ``query_content``. - """ - - iam_policy_analysis_query: 'IamPolicyAnalysisQuery' = proto.Field( - proto.MESSAGE, - number=1, - oneof='query_content', - message='IamPolicyAnalysisQuery', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - description: str = proto.Field( - proto.STRING, - number=2, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - creator: str = proto.Field( - proto.STRING, - number=4, - ) - last_update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - last_updater: str = proto.Field( - proto.STRING, - number=6, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - content: QueryContent = proto.Field( - proto.MESSAGE, - number=8, - message=QueryContent, - ) - - -class CreateSavedQueryRequest(proto.Message): - r"""Request to create a saved query. - - Attributes: - parent (str): - Required. The name of the project/folder/organization where - this saved_query should be created in. It can only be an - organization number (such as "organizations/123"), a folder - number (such as "folders/123"), a project ID (such as - "projects/my-project-id"), or a project number (such as - "projects/12345"). - saved_query (google.cloud.asset_v1.types.SavedQuery): - Required. The saved_query details. The ``name`` field must - be empty as it will be generated based on the parent and - saved_query_id. - saved_query_id (str): - Required. The ID to use for the saved query, which must be - unique in the specified parent. It will become the final - component of the saved query's resource name. - - This value should be 4-63 characters, and valid characters - are ``[a-z][0-9]-``. - - Notice that this field is required in the saved query - creation, and the ``name`` field of the ``saved_query`` will - be ignored. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - saved_query: 'SavedQuery' = proto.Field( - proto.MESSAGE, - number=2, - message='SavedQuery', - ) - saved_query_id: str = proto.Field( - proto.STRING, - number=3, - ) - - -class GetSavedQueryRequest(proto.Message): - r"""Request to get a saved query. - - Attributes: - name (str): - Required. The name of the saved query and it must be in the - format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListSavedQueriesRequest(proto.Message): - r"""Request to list saved queries. - - Attributes: - parent (str): - Required. The parent - project/folder/organization whose savedQueries - are to be listed. It can only be using - project/folder/organization number (such as - "folders/12345")", or a project ID (such as - "projects/my-project-id"). - filter (str): - Optional. The expression to filter resources. The expression - is a list of zero or more restrictions combined via logical - operators ``AND`` and ``OR``. When ``AND`` and ``OR`` are - both used in the expression, parentheses must be - appropriately used to group the combinations. The expression - may also contain regular expressions. - - See https://google.aip.dev/160 for more information on the - grammar. - page_size (int): - Optional. The maximum number of saved queries - to return per page. The service may return fewer - than this value. If unspecified, at most 50 will - be returned. The maximum value is 1000; values - above 1000 will be coerced to 1000. - page_token (str): - Optional. A page token, received from a previous - ``ListSavedQueries`` call. Provide this to retrieve the - subsequent page. - - When paginating, all other parameters provided to - ``ListSavedQueries`` must match the call that provided the - page token. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class ListSavedQueriesResponse(proto.Message): - r"""Response of listing saved queries. - - Attributes: - saved_queries (MutableSequence[google.cloud.asset_v1.types.SavedQuery]): - A list of savedQueries. - 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 - - saved_queries: MutableSequence['SavedQuery'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='SavedQuery', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class UpdateSavedQueryRequest(proto.Message): - r"""Request to update a saved query. - - Attributes: - saved_query (google.cloud.asset_v1.types.SavedQuery): - Required. The saved query to update. - - The saved query's ``name`` field is used to identify the one - to update, which has format as below: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. The list of fields to update. - """ - - saved_query: 'SavedQuery' = proto.Field( - proto.MESSAGE, - number=1, - message='SavedQuery', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteSavedQueryRequest(proto.Message): - r"""Request to delete a saved query. - - Attributes: - name (str): - Required. The name of the saved query to delete. It must be - in the format of: - - - projects/project_number/savedQueries/saved_query_id - - folders/folder_number/savedQueries/saved_query_id - - organizations/organization_number/savedQueries/saved_query_id - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AnalyzeMoveRequest(proto.Message): - r"""The request message for performing resource move analysis. - - Attributes: - resource (str): - Required. Name of the resource to perform the - analysis against. Only Google Cloud projects are - supported as of today. Hence, this can only be a - project ID (such as "projects/my-project-id") or - a project number (such as "projects/12345"). - destination_parent (str): - Required. Name of the Google Cloud folder or - organization to reparent the target resource. - The analysis will be performed against - hypothetically moving the resource to this - specified desitination parent. This can only be - a folder number (such as "folders/123") or an - organization number (such as - "organizations/123"). - view (google.cloud.asset_v1.types.AnalyzeMoveRequest.AnalysisView): - Analysis view indicating what information - should be included in the analysis response. If - unspecified, the default view is FULL. - """ - class AnalysisView(proto.Enum): - r"""View enum for supporting partial analysis responses. - - Values: - ANALYSIS_VIEW_UNSPECIFIED (0): - The default/unset value. - The API will default to the FULL view. - FULL (1): - Full analysis including all level of impacts - of the specified resource move. - BASIC (2): - Basic analysis only including blockers which - will prevent the specified resource move at - runtime. - """ - ANALYSIS_VIEW_UNSPECIFIED = 0 - FULL = 1 - BASIC = 2 - - resource: str = proto.Field( - proto.STRING, - number=1, - ) - destination_parent: str = proto.Field( - proto.STRING, - number=2, - ) - view: AnalysisView = proto.Field( - proto.ENUM, - number=3, - enum=AnalysisView, - ) - - -class AnalyzeMoveResponse(proto.Message): - r"""The response message for resource move analysis. - - Attributes: - move_analysis (MutableSequence[google.cloud.asset_v1.types.MoveAnalysis]): - The list of analyses returned from performing - the intended resource move analysis. The - analysis is grouped by different Google Cloud - services. - """ - - move_analysis: MutableSequence['MoveAnalysis'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MoveAnalysis', - ) - - -class MoveAnalysis(proto.Message): - r"""A message to group the analysis information. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - display_name (str): - The user friendly display name of the - analysis. E.g. IAM, organization policy etc. - analysis (google.cloud.asset_v1.types.MoveAnalysisResult): - Analysis result of moving the target - resource. - - This field is a member of `oneof`_ ``result``. - error (google.rpc.status_pb2.Status): - Description of error encountered when - performing the analysis. - - This field is a member of `oneof`_ ``result``. - """ - - display_name: str = proto.Field( - proto.STRING, - number=1, - ) - analysis: 'MoveAnalysisResult' = proto.Field( - proto.MESSAGE, - number=2, - oneof='result', - message='MoveAnalysisResult', - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - oneof='result', - message=status_pb2.Status, - ) - - -class MoveAnalysisResult(proto.Message): - r"""An analysis result including blockers and warnings. - - Attributes: - blockers (MutableSequence[google.cloud.asset_v1.types.MoveImpact]): - Blocking information that would prevent the - target resource from moving to the specified - destination at runtime. - warnings (MutableSequence[google.cloud.asset_v1.types.MoveImpact]): - Warning information indicating that moving - the target resource to the specified destination - might be unsafe. This can include important - policy information and configuration changes, - but will not block moves at runtime. - """ - - blockers: MutableSequence['MoveImpact'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='MoveImpact', - ) - warnings: MutableSequence['MoveImpact'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='MoveImpact', - ) - - -class MoveImpact(proto.Message): - r"""A message to group impacts of moving the target resource. - - Attributes: - detail (str): - User friendly impact detail in a free form - message. - """ - - detail: str = proto.Field( - proto.STRING, - number=1, - ) - - -class QueryAssetsOutputConfig(proto.Message): - r"""Output configuration query assets. - - Attributes: - bigquery_destination (google.cloud.asset_v1.types.QueryAssetsOutputConfig.BigQueryDestination): - BigQuery destination where the query results - will be saved. - """ - - class BigQueryDestination(proto.Message): - r"""BigQuery destination. - - Attributes: - dataset (str): - Required. The BigQuery dataset where the - query results will be saved. It has the format - of "projects/{projectId}/datasets/{datasetId}". - table (str): - Required. The BigQuery table where the query - results will be saved. If this table does not - exist, a new table with the given name will be - created. - write_disposition (str): - Specifies the action that occurs if the destination table or - partition already exists. The following values are - supported: - - - WRITE_TRUNCATE: If the table or partition already exists, - BigQuery overwrites the entire table or all the - partitions data. - - WRITE_APPEND: If the table or partition already exists, - BigQuery appends the data to the table or the latest - partition. - - WRITE_EMPTY: If the table already exists and contains - data, a 'duplicate' error is returned in the job result. - - The default value is WRITE_EMPTY. - """ - - dataset: str = proto.Field( - proto.STRING, - number=1, - ) - table: str = proto.Field( - proto.STRING, - number=2, - ) - write_disposition: str = proto.Field( - proto.STRING, - number=3, - ) - - bigquery_destination: BigQueryDestination = proto.Field( - proto.MESSAGE, - number=1, - message=BigQueryDestination, - ) - - -class QueryAssetsRequest(proto.Message): - r"""QueryAssets request. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The relative name of the root asset. This can only - be an organization number (such as "organizations/123"), a - project ID (such as "projects/my-project-id"), or a project - number (such as "projects/12345"), or a folder number (such - as "folders/123"). - - Only assets belonging to the ``parent`` will be returned. - statement (str): - Optional. A SQL statement that's compatible with `BigQuery - SQL `__. - - This field is a member of `oneof`_ ``query``. - job_reference (str): - Optional. Reference to the query job, which is from the - ``QueryAssetsResponse`` of previous ``QueryAssets`` call. - - This field is a member of `oneof`_ ``query``. - page_size (int): - Optional. The maximum number of rows to return in the - results. Responses are limited to 10 MB and 1000 rows. - - By default, the maximum row count is 1000. When the byte or - row count limit is reached, the rest of the query results - will be paginated. - - The field will be ignored when [output_config] is specified. - page_token (str): - Optional. A page token received from previous - ``QueryAssets``. - - The field will be ignored when [output_config] is specified. - timeout (google.protobuf.duration_pb2.Duration): - Optional. Specifies the maximum amount of time that the - client is willing to wait for the query to complete. By - default, this limit is 5 min for the first query, and 1 - minute for the following queries. If the query is complete, - the ``done`` field in the ``QueryAssetsResponse`` is true, - otherwise false. - - Like BigQuery `jobs.query - API `__ - The call is not guaranteed to wait for the specified - timeout; it typically returns after around 200 seconds - (200,000 milliseconds), even if the query is not complete. - - The field will be ignored when [output_config] is specified. - read_time_window (google.cloud.asset_v1.types.TimeWindow): - Optional. [start_time] is required. [start_time] must be - less than [end_time] Defaults [end_time] to now if - [start_time] is set and [end_time] isn't. Maximum permitted - time range is 7 days. - - This field is a member of `oneof`_ ``time``. - read_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. Queries cloud assets as they - appeared at the specified point in time. - - This field is a member of `oneof`_ ``time``. - output_config (google.cloud.asset_v1.types.QueryAssetsOutputConfig): - Optional. Destination where the query results will be saved. - - When this field is specified, the query results won't be - saved in the [QueryAssetsResponse.query_result]. Instead - [QueryAssetsResponse.output_config] will be set. - - Meanwhile, [QueryAssetsResponse.job_reference] will be set - and can be used to check the status of the query job when - passed to a following [QueryAssets] API call. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - statement: str = proto.Field( - proto.STRING, - number=2, - oneof='query', - ) - job_reference: str = proto.Field( - proto.STRING, - number=3, - oneof='query', - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - timeout: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=6, - message=duration_pb2.Duration, - ) - read_time_window: gca_assets.TimeWindow = proto.Field( - proto.MESSAGE, - number=7, - oneof='time', - message=gca_assets.TimeWindow, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=8, - oneof='time', - message=timestamp_pb2.Timestamp, - ) - output_config: 'QueryAssetsOutputConfig' = proto.Field( - proto.MESSAGE, - number=9, - message='QueryAssetsOutputConfig', - ) - - -class QueryAssetsResponse(proto.Message): - r"""QueryAssets response. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - job_reference (str): - Reference to a query job. - done (bool): - The query response, which can be either an ``error`` or a - valid ``response``. - - If ``done`` == ``false`` and the query result is being saved - in a output, the output_config field will be set. If - ``done`` == ``true``, exactly one of ``error``, - ``query_result`` or ``output_config`` will be set. - error (google.rpc.status_pb2.Status): - Error status. - - This field is a member of `oneof`_ ``response``. - query_result (google.cloud.asset_v1.types.QueryResult): - Result of the query. - - This field is a member of `oneof`_ ``response``. - output_config (google.cloud.asset_v1.types.QueryAssetsOutputConfig): - Output configuration which indicates instead - of being returned in API response on the fly, - the query result will be saved in a specific - output. - - This field is a member of `oneof`_ ``response``. - """ - - job_reference: str = proto.Field( - proto.STRING, - number=1, - ) - done: bool = proto.Field( - proto.BOOL, - number=2, - ) - error: status_pb2.Status = proto.Field( - proto.MESSAGE, - number=3, - oneof='response', - message=status_pb2.Status, - ) - query_result: 'QueryResult' = proto.Field( - proto.MESSAGE, - number=4, - oneof='response', - message='QueryResult', - ) - output_config: 'QueryAssetsOutputConfig' = proto.Field( - proto.MESSAGE, - number=5, - oneof='response', - message='QueryAssetsOutputConfig', - ) - - -class QueryResult(proto.Message): - r"""Execution results of the query. - - The result is formatted as rows represented by BigQuery compatible - [schema]. When pagination is necessary, it will contains the page - token to retrieve the results of following pages. - - Attributes: - rows (MutableSequence[google.protobuf.struct_pb2.Struct]): - Each row hold a query result in the format of ``Struct``. - schema (google.cloud.asset_v1.types.TableSchema): - Describes the format of the [rows]. - next_page_token (str): - Token to retrieve the next page of the - results. - total_rows (int): - Total rows of the whole query results. - """ - - @property - def raw_page(self): - return self - - rows: MutableSequence[struct_pb2.Struct] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=struct_pb2.Struct, - ) - schema: 'TableSchema' = proto.Field( - proto.MESSAGE, - number=2, - message='TableSchema', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - total_rows: int = proto.Field( - proto.INT64, - number=4, - ) - - -class TableSchema(proto.Message): - r"""BigQuery Compatible table schema. - - Attributes: - fields (MutableSequence[google.cloud.asset_v1.types.TableFieldSchema]): - Describes the fields in a table. - """ - - fields: MutableSequence['TableFieldSchema'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='TableFieldSchema', - ) - - -class TableFieldSchema(proto.Message): - r"""A field in TableSchema. - - Attributes: - field (str): - The field name. The name must contain only letters (a-z, - A-Z), numbers (0-9), or underscores (_), and must start with - a letter or underscore. The maximum length is 128 - characters. - type_ (str): - The field data type. Possible values include - - - STRING - - BYTES - - INTEGER - - FLOAT - - BOOLEAN - - TIMESTAMP - - DATE - - TIME - - DATETIME - - GEOGRAPHY, - - NUMERIC, - - BIGNUMERIC, - - RECORD (where RECORD indicates that the field contains a - nested schema). - mode (str): - The field mode. Possible values include - NULLABLE, REQUIRED and REPEATED. The default - value is NULLABLE. - fields (MutableSequence[google.cloud.asset_v1.types.TableFieldSchema]): - Describes the nested schema fields if the - type property is set to RECORD. - """ - - field: str = proto.Field( - proto.STRING, - number=1, - ) - type_: str = proto.Field( - proto.STRING, - number=2, - ) - mode: str = proto.Field( - proto.STRING, - number=3, - ) - fields: MutableSequence['TableFieldSchema'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='TableFieldSchema', - ) - - -class BatchGetEffectiveIamPoliciesRequest(proto.Message): - r"""A request message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - - Attributes: - scope (str): - Required. Only IAM policies on or below the scope will be - returned. - - This can only be an organization number (such as - "organizations/123"), a folder number (such as - "folders/123"), a project ID (such as - "projects/my-project-id"), or a project number (such as - "projects/12345"). - - To know how to get organization id, visit - `here `__. - - To know how to get folder or project id, visit - `here `__. - names (MutableSequence[str]): - Required. The names refer to the [full_resource_names] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of `searchable asset - types `__. - A maximum of 20 resources' effective policies can be - retrieved in a batch. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - -class BatchGetEffectiveIamPoliciesResponse(proto.Message): - r"""A response message for - [AssetService.BatchGetEffectiveIamPolicies][google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies]. - - Attributes: - policy_results (MutableSequence[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy]): - The effective policies for a batch of resources. Note that - the results order is the same as the order of - [BatchGetEffectiveIamPoliciesRequest.names][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesRequest.names]. - When a resource does not have any effective IAM policies, - its corresponding policy_result will contain empty - [EffectiveIamPolicy.policies][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.policies]. - """ - - class EffectiveIamPolicy(proto.Message): - r"""The effective IAM policies on one resource. - - Attributes: - full_resource_name (str): - The [full_resource_name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - for which the - [policies][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.policies] - are computed. This is one of the - [BatchGetEffectiveIamPoliciesRequest.names][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesRequest.names] - the caller provides in the request. - policies (MutableSequence[google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo]): - The effective policies for the - [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name]. - - These policies include the policy set on the - [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name] - and those set on its parents and ancestors up to the - [BatchGetEffectiveIamPoliciesRequest.scope][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesRequest.scope]. - Note that these policies are not filtered according to the - resource type of the - [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name]. - - These policies are hierarchically ordered by - [PolicyInfo.attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource] - starting from - [full_resource_name][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.full_resource_name] - itself to its parents and ancestors, such that policies[i]'s - [PolicyInfo.attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource] - is the child of policies[i+1]'s - [PolicyInfo.attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource], - if policies[i+1] exists. - """ - - class PolicyInfo(proto.Message): - r"""The IAM policy and its attached resource. - - Attributes: - attached_resource (str): - The full resource name the - [policy][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.policy] - is directly attached to. - policy (google.iam.v1.policy_pb2.Policy): - The IAM policy that's directly attached to the - [attached_resource][google.cloud.asset.v1.BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo.attached_resource]. - """ - - attached_resource: str = proto.Field( - proto.STRING, - number=1, - ) - policy: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=2, - message=policy_pb2.Policy, - ) - - full_resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - policies: MutableSequence['BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='BatchGetEffectiveIamPoliciesResponse.EffectiveIamPolicy.PolicyInfo', - ) - - policy_results: MutableSequence[EffectiveIamPolicy] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=EffectiveIamPolicy, - ) - - -class AnalyzerOrgPolicy(proto.Message): - r"""This organization policy message is a modified version of the - one defined in the Organization Policy system. This message - contains several fields defined in the original organization - policy with some new fields for analysis purpose. - - Attributes: - attached_resource (str): - The [full resource name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of an organization/folder/project resource where this - organization policy is set. - - Notice that some type of constraints are defined with - default policy. This field will be empty for them. - applied_resource (str): - The [full resource name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of an organization/folder/project resource where this - organization policy applies to. - - For any user defined org policies, this field has the same - value as the [attached_resource] field. Only for default - policy, this field has the different value. - rules (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy.Rule]): - List of rules for this organization policy. - inherit_from_parent (bool): - If ``inherit_from_parent`` is true, Rules set higher up in - the hierarchy (up to the closest root) are inherited and - present in the effective policy. If it is false, then no - rules are inherited, and this policy becomes the effective - root for evaluation. - reset (bool): - Ignores policies set above this resource and restores the - default behavior of the constraint at this resource. This - field can be set in policies for either list or boolean - constraints. If set, ``rules`` must be empty and - ``inherit_from_parent`` must be set to false. - """ - - class Rule(proto.Message): - r"""This rule message is a customized version of the one defined - in the Organization Policy system. In addition to the fields - defined in the original organization policy, it contains - additional field(s) under specific circumstances to support - analysis results. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - values (google.cloud.asset_v1.types.AnalyzerOrgPolicy.Rule.StringValues): - List of values to be used for this - PolicyRule. This field can be set only in - Policies for list constraints. - - This field is a member of `oneof`_ ``kind``. - allow_all (bool): - Setting this to true means that all values - are allowed. This field can be set only in - Policies for list constraints. - - This field is a member of `oneof`_ ``kind``. - deny_all (bool): - Setting this to true means that all values - are denied. This field can be set only in - Policies for list constraints. - - This field is a member of `oneof`_ ``kind``. - enforce (bool): - If ``true``, then the ``Policy`` is enforced. If ``false``, - then any configuration is acceptable. This field can be set - only in Policies for boolean constraints. - - This field is a member of `oneof`_ ``kind``. - condition (google.type.expr_pb2.Expr): - The evaluating condition for this rule. - """ - - class StringValues(proto.Message): - r"""The string values for the list constraints. - - Attributes: - allowed_values (MutableSequence[str]): - List of values allowed at this resource. - denied_values (MutableSequence[str]): - List of values denied at this resource. - """ - - allowed_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - denied_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - - values: 'AnalyzerOrgPolicy.Rule.StringValues' = proto.Field( - proto.MESSAGE, - number=3, - oneof='kind', - message='AnalyzerOrgPolicy.Rule.StringValues', - ) - allow_all: bool = proto.Field( - proto.BOOL, - number=4, - oneof='kind', - ) - deny_all: bool = proto.Field( - proto.BOOL, - number=5, - oneof='kind', - ) - enforce: bool = proto.Field( - proto.BOOL, - number=6, - oneof='kind', - ) - condition: expr_pb2.Expr = proto.Field( - proto.MESSAGE, - number=7, - message=expr_pb2.Expr, - ) - - attached_resource: str = proto.Field( - proto.STRING, - number=1, - ) - applied_resource: str = proto.Field( - proto.STRING, - number=5, - ) - rules: MutableSequence[Rule] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=Rule, - ) - inherit_from_parent: bool = proto.Field( - proto.BOOL, - number=3, - ) - reset: bool = proto.Field( - proto.BOOL, - number=4, - ) - - -class AnalyzerOrgPolicyConstraint(proto.Message): - r"""The organization policy constraint definition. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - google_defined_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint): - The definition of the canned constraint - defined by Google. - - This field is a member of `oneof`_ ``constraint_definition``. - custom_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.CustomConstraint): - The definition of the custom constraint. - - This field is a member of `oneof`_ ``constraint_definition``. - """ - - class Constraint(proto.Message): - r"""The definition of a constraint. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The unique name of the constraint. Format of the name should - be - - - ``constraints/{constraint_name}`` - - For example, - ``constraints/compute.disableSerialPortAccess``. - display_name (str): - The human readable name of the constraint. - description (str): - Detailed description of what this ``Constraint`` controls as - well as how and where it is enforced. - constraint_default (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint.ConstraintDefault): - The evaluation behavior of this constraint in - the absence of 'Policy'. - list_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint.ListConstraint): - Defines this constraint as being a - ListConstraint. - - This field is a member of `oneof`_ ``constraint_type``. - boolean_constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.Constraint.BooleanConstraint): - Defines this constraint as being a - BooleanConstraint. - - This field is a member of `oneof`_ ``constraint_type``. - """ - class ConstraintDefault(proto.Enum): - r"""Specifies the default behavior in the absence of any ``Policy`` for - the ``Constraint``. This must not be - ``CONSTRAINT_DEFAULT_UNSPECIFIED``. - - Values: - CONSTRAINT_DEFAULT_UNSPECIFIED (0): - This is only used for distinguishing unset - values and should never be used. - ALLOW (1): - Indicate that all values are allowed for list - constraints. Indicate that enforcement is off - for boolean constraints. - DENY (2): - Indicate that all values are denied for list - constraints. Indicate that enforcement is on for - boolean constraints. - """ - CONSTRAINT_DEFAULT_UNSPECIFIED = 0 - ALLOW = 1 - DENY = 2 - - class ListConstraint(proto.Message): - r"""A ``Constraint`` that allows or disallows a list of string values, - which are configured by an organization's policy administrator with - a ``Policy``. - - Attributes: - supports_in (bool): - Indicates whether values grouped into categories can be used - in ``Policy.allowed_values`` and ``Policy.denied_values``. - For example, ``"in:Python"`` would match any value in the - 'Python' group. - supports_under (bool): - Indicates whether subtrees of Cloud Resource Manager - resource hierarchy can be used in ``Policy.allowed_values`` - and ``Policy.denied_values``. For example, - ``"under:folders/123"`` would match any resource under the - 'folders/123' folder. - """ - - supports_in: bool = proto.Field( - proto.BOOL, - number=1, - ) - supports_under: bool = proto.Field( - proto.BOOL, - number=2, - ) - - class BooleanConstraint(proto.Message): - r"""A ``Constraint`` that is either enforced or not. - - For example a constraint - ``constraints/compute.disableSerialPortAccess``. If it is enforced - on a VM instance, serial port connections will not be opened to that - instance. - - """ - - 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, - ) - constraint_default: 'AnalyzerOrgPolicyConstraint.Constraint.ConstraintDefault' = proto.Field( - proto.ENUM, - number=4, - enum='AnalyzerOrgPolicyConstraint.Constraint.ConstraintDefault', - ) - list_constraint: 'AnalyzerOrgPolicyConstraint.Constraint.ListConstraint' = proto.Field( - proto.MESSAGE, - number=5, - oneof='constraint_type', - message='AnalyzerOrgPolicyConstraint.Constraint.ListConstraint', - ) - boolean_constraint: 'AnalyzerOrgPolicyConstraint.Constraint.BooleanConstraint' = proto.Field( - proto.MESSAGE, - number=6, - oneof='constraint_type', - message='AnalyzerOrgPolicyConstraint.Constraint.BooleanConstraint', - ) - - class CustomConstraint(proto.Message): - r"""The definition of a custom constraint. - - Attributes: - name (str): - Name of the constraint. This is unique within the - organization. Format of the name should be - - - ``organizations/{organization_id}/customConstraints/{custom_constraint_id}`` - - Example : - "organizations/123/customConstraints/custom.createOnlyE2TypeVms". - resource_types (MutableSequence[str]): - The Resource Instance type on which this policy applies to. - Format will be of the form : "/" Example: - - - ``compute.googleapis.com/Instance``. - method_types (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.CustomConstraint.MethodType]): - All the operations being applied for this - constraint. - condition (str): - Organization Policy condition/expression. For example: - ``resource.instanceName.matches("[production|test]_.*_(\d)+")'`` - or, ``resource.management.auto_upgrade == true`` - action_type (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint.CustomConstraint.ActionType): - Allow or deny type. - display_name (str): - One line display name for the UI. - description (str): - Detailed information about this custom policy - constraint. - """ - class MethodType(proto.Enum): - r"""The operation in which this constraint will be applied. For example: - If the constraint applies only when create VMs, the method_types - will be "CREATE" only. If the constraint applied when create or - delete VMs, the method_types will be "CREATE" and "DELETE". - - Values: - METHOD_TYPE_UNSPECIFIED (0): - Unspecified. Will results in user error. - CREATE (1): - Constraint applied when creating the - resource. - UPDATE (2): - Constraint applied when updating the - resource. - DELETE (3): - Constraint applied when deleting the - resource. - """ - METHOD_TYPE_UNSPECIFIED = 0 - CREATE = 1 - UPDATE = 2 - DELETE = 3 - - class ActionType(proto.Enum): - r"""Allow or deny type. - - Values: - ACTION_TYPE_UNSPECIFIED (0): - Unspecified. Will results in user error. - ALLOW (1): - Allowed action type. - DENY (2): - Deny action type. - """ - ACTION_TYPE_UNSPECIFIED = 0 - ALLOW = 1 - DENY = 2 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - resource_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - method_types: MutableSequence['AnalyzerOrgPolicyConstraint.CustomConstraint.MethodType'] = proto.RepeatedField( - proto.ENUM, - number=3, - enum='AnalyzerOrgPolicyConstraint.CustomConstraint.MethodType', - ) - condition: str = proto.Field( - proto.STRING, - number=4, - ) - action_type: 'AnalyzerOrgPolicyConstraint.CustomConstraint.ActionType' = proto.Field( - proto.ENUM, - number=5, - enum='AnalyzerOrgPolicyConstraint.CustomConstraint.ActionType', - ) - display_name: str = proto.Field( - proto.STRING, - number=6, - ) - description: str = proto.Field( - proto.STRING, - number=7, - ) - - google_defined_constraint: Constraint = proto.Field( - proto.MESSAGE, - number=1, - oneof='constraint_definition', - message=Constraint, - ) - custom_constraint: CustomConstraint = proto.Field( - proto.MESSAGE, - number=2, - oneof='constraint_definition', - message=CustomConstraint, - ) - - -class AnalyzeOrgPoliciesRequest(proto.Message): - r"""A request message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - scope (str): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - constraint (str): - Required. The name of the constraint to - analyze organization policies for. The response - only contains analyzed organization policies for - the provided constraint. - filter (str): - The expression to filter - [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. - The only supported field is - ``consolidated_policy.attached_resource``, and the only - supported operator is ``=``. - - Example: - consolidated_policy.attached_resource="//cloudresourcemanager.googleapis.com/folders/001" - will return the org policy results of"folders/001". - page_size (int): - The maximum number of items to return per page. If - unspecified, - [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results] - will contain 20 items with a maximum of 200. - - This field is a member of `oneof`_ ``_page_size``. - page_token (str): - The pagination token to retrieve the next - page. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - constraint: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - - -class AnalyzeOrgPoliciesResponse(proto.Message): - r"""The response message for - [AssetService.AnalyzeOrgPolicies][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies]. - - Attributes: - org_policy_results (MutableSequence[google.cloud.asset_v1.types.AnalyzeOrgPoliciesResponse.OrgPolicyResult]): - The organization policies under the - [AnalyzeOrgPoliciesRequest.scope][google.cloud.asset.v1.AnalyzeOrgPoliciesRequest.scope] - with the - [AnalyzeOrgPoliciesRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPoliciesRequest.constraint]. - constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint): - The definition of the constraint in the - request. - next_page_token (str): - The page token to fetch the next page for - [AnalyzeOrgPoliciesResponse.org_policy_results][google.cloud.asset.v1.AnalyzeOrgPoliciesResponse.org_policy_results]. - """ - - class OrgPolicyResult(proto.Message): - r"""The organization policy result to the query. - - Attributes: - consolidated_policy (google.cloud.asset_v1.types.AnalyzerOrgPolicy): - The consolidated organization policy for the analyzed - resource. The consolidated organization policy is computed - by merging and evaluating - [AnalyzeOrgPoliciesResponse.policy_bundle][]. The evaluation - will respect the organization policy `hierarchy - rules `__. - policy_bundle (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy]): - The ordered list of all organization policies from the - [AnalyzeOrgPoliciesResponse.OrgPolicyResult.consolidated_policy.attached_resource][]. - to the scope specified in the request. - - If the constraint is defined with default policy, it will - also appear in the list. - """ - - consolidated_policy: 'AnalyzerOrgPolicy' = proto.Field( - proto.MESSAGE, - number=1, - message='AnalyzerOrgPolicy', - ) - policy_bundle: MutableSequence['AnalyzerOrgPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='AnalyzerOrgPolicy', - ) - - @property - def raw_page(self): - return self - - org_policy_results: MutableSequence[OrgPolicyResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=OrgPolicyResult, - ) - constraint: 'AnalyzerOrgPolicyConstraint' = proto.Field( - proto.MESSAGE, - number=2, - message='AnalyzerOrgPolicyConstraint', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class AnalyzeOrgPolicyGovernedContainersRequest(proto.Message): - r"""A request message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - scope (str): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. The - output containers will also be limited to the ones governed - by those in-scope organization policies. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - constraint (str): - Required. The name of the constraint to - analyze governed containers for. The analysis - only contains organization policies for the - provided constraint. - filter (str): - The expression to filter the governed containers in result. - The only supported field is ``parent``, and the only - supported operator is ``=``. - - Example: - parent="//cloudresourcemanager.googleapis.com/folders/001" - will return all containers under "folders/001". - page_size (int): - The maximum number of items to return per page. If - unspecified, - [AnalyzeOrgPolicyGovernedContainersResponse.governed_containers][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.governed_containers] - will contain 100 items with a maximum of 200. - - This field is a member of `oneof`_ ``_page_size``. - page_token (str): - The pagination token to retrieve the next - page. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - constraint: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - - -class AnalyzeOrgPolicyGovernedContainersResponse(proto.Message): - r"""The response message for - [AssetService.AnalyzeOrgPolicyGovernedContainers][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers]. - - Attributes: - governed_containers (MutableSequence[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer]): - The list of the analyzed governed containers. - constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint): - The definition of the constraint in the - request. - next_page_token (str): - The page token to fetch the next page for - [AnalyzeOrgPolicyGovernedContainersResponse.governed_containers][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.governed_containers]. - """ - - class GovernedContainer(proto.Message): - r"""The organization/folder/project resource governed by organization - policies of - [AnalyzeOrgPolicyGovernedContainersRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersRequest.constraint]. - - Attributes: - full_resource_name (str): - The [full resource name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of an organization/folder/project resource. - parent (str): - The [full resource name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of the parent of - [AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.full_resource_name][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.full_resource_name]. - consolidated_policy (google.cloud.asset_v1.types.AnalyzerOrgPolicy): - The consolidated organization policy for the analyzed - resource. The consolidated organization policy is computed - by merging and evaluating - [AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.policy_bundle][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer.policy_bundle]. - The evaluation will respect the organization policy - `hierarchy - rules `__. - policy_bundle (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy]): - The ordered list of all organization policies from the - [AnalyzeOrgPoliciesResponse.OrgPolicyResult.consolidated_policy.attached_resource][]. - to the scope specified in the request. - - If the constraint is defined with default policy, it will - also appear in the list. - """ - - full_resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - consolidated_policy: 'AnalyzerOrgPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='AnalyzerOrgPolicy', - ) - policy_bundle: MutableSequence['AnalyzerOrgPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AnalyzerOrgPolicy', - ) - - @property - def raw_page(self): - return self - - governed_containers: MutableSequence[GovernedContainer] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=GovernedContainer, - ) - constraint: 'AnalyzerOrgPolicyConstraint' = proto.Field( - proto.MESSAGE, - number=2, - message='AnalyzerOrgPolicyConstraint', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -class AnalyzeOrgPolicyGovernedAssetsRequest(proto.Message): - r"""A request message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - scope (str): - Required. The organization to scope the request. Only - organization policies within the scope will be analyzed. The - output assets will also be limited to the ones governed by - those in-scope organization policies. - - - organizations/{ORGANIZATION_NUMBER} (e.g., - "organizations/123456") - constraint (str): - Required. The name of the constraint to - analyze governed assets for. The analysis only - contains analyzed organization policies for the - provided constraint. - filter (str): - The expression to filter the governed assets in result. The - only supported fields for governed resources are - ``governed_resource.project`` and - ``governed_resource.folders``. The only supported fields for - governed iam policies are ``governed_iam_policy.project`` - and ``governed_iam_policy.folders``. The only supported - operator is ``=``. - - Example 1: governed_resource.project="projects/12345678" - filter will return all governed resources under - projects/12345678 including the project ifself, if - applicable. - - Example 2: governed_iam_policy.folders="folders/12345678" - filter will return all governed iam policies under - folders/12345678, if applicable. - page_size (int): - The maximum number of items to return per page. If - unspecified, - [AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets] - will contain 100 items with a maximum of 200. - - This field is a member of `oneof`_ ``_page_size``. - page_token (str): - The pagination token to retrieve the next - page. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - constraint: str = proto.Field( - proto.STRING, - number=2, - ) - filter: str = proto.Field( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - - -class AnalyzeOrgPolicyGovernedAssetsResponse(proto.Message): - r"""The response message for - [AssetService.AnalyzeOrgPolicyGovernedAssets][google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets]. - - Attributes: - governed_assets (MutableSequence[google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset]): - The list of the analyzed governed assets. - constraint (google.cloud.asset_v1.types.AnalyzerOrgPolicyConstraint): - The definition of the constraint in the - request. - next_page_token (str): - The page token to fetch the next page for - [AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.governed_assets]. - """ - - class GovernedResource(proto.Message): - r"""The Google Cloud resources governed by the organization policies of - the - [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. - - Attributes: - full_resource_name (str): - The [full resource name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of the Google Cloud resource. - parent (str): - The [full resource name] - (https://cloud.google.com/asset-inventory/docs/resource-name-format) - of the parent of - [AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource.full_resource_name][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource.full_resource_name]. - project (str): - The project that this resource belongs to, in the format of - projects/{PROJECT_NUMBER}. This field is available when the - resource belongs to a project. - folders (MutableSequence[str]): - The folder(s) that this resource belongs to, in the format - of folders/{FOLDER_NUMBER}. This field is available when the - resource belongs (directly or cascadingly) to one or more - folders. - organization (str): - The organization that this resource belongs to, in the - format of organizations/{ORGANIZATION_NUMBER}. This field is - available when the resource belongs (directly or - cascadingly) to an organization. - """ - - full_resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - parent: str = proto.Field( - proto.STRING, - number=2, - ) - project: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - organization: str = proto.Field( - proto.STRING, - number=7, - ) - - class GovernedIamPolicy(proto.Message): - r"""The IAM policies governed by the organization policies of the - [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. - - Attributes: - attached_resource (str): - The full resource name of the resource on which this IAM - policy is set. Example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Cloud Asset Inventory Resource Name - Format `__ - for more information. - policy (google.iam.v1.policy_pb2.Policy): - The IAM policy directly set on the given - resource. - project (str): - The project that this IAM policy belongs to, in the format - of projects/{PROJECT_NUMBER}. This field is available when - the IAM policy belongs to a project. - folders (MutableSequence[str]): - The folder(s) that this IAM policy belongs to, in the format - of folders/{FOLDER_NUMBER}. This field is available when the - IAM policy belongs (directly or cascadingly) to one or more - folders. - organization (str): - The organization that this IAM policy belongs to, in the - format of organizations/{ORGANIZATION_NUMBER}. This field is - available when the IAM policy belongs (directly or - cascadingly) to an organization. - """ - - attached_resource: str = proto.Field( - proto.STRING, - number=1, - ) - policy: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=2, - message=policy_pb2.Policy, - ) - project: str = proto.Field( - proto.STRING, - number=5, - ) - folders: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - organization: str = proto.Field( - proto.STRING, - number=7, - ) - - class GovernedAsset(proto.Message): - r"""Represents a Google Cloud asset(resource or IAM policy) governed by - the organization policies of the - [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - governed_resource (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource): - A Google Cloud resource governed by the organization - policies of the - [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. - - This field is a member of `oneof`_ ``governed_asset``. - governed_iam_policy (google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedIamPolicy): - An IAM policy governed by the organization policies of the - [AnalyzeOrgPolicyGovernedAssetsRequest.constraint][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsRequest.constraint]. - - This field is a member of `oneof`_ ``governed_asset``. - consolidated_policy (google.cloud.asset_v1.types.AnalyzerOrgPolicy): - The consolidated policy for the analyzed asset. The - consolidated policy is computed by merging and evaluating - [AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset.policy_bundle][google.cloud.asset.v1.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset.policy_bundle]. - The evaluation will respect the organization policy - `hierarchy - rules `__. - policy_bundle (MutableSequence[google.cloud.asset_v1.types.AnalyzerOrgPolicy]): - The ordered list of all organization policies from the - [AnalyzeOrgPoliciesResponse.OrgPolicyResult.consolidated_policy.attached_resource][] - to the scope specified in the request. - - If the constraint is defined with default policy, it will - also appear in the list. - """ - - governed_resource: 'AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource' = proto.Field( - proto.MESSAGE, - number=1, - oneof='governed_asset', - message='AnalyzeOrgPolicyGovernedAssetsResponse.GovernedResource', - ) - governed_iam_policy: 'AnalyzeOrgPolicyGovernedAssetsResponse.GovernedIamPolicy' = proto.Field( - proto.MESSAGE, - number=2, - oneof='governed_asset', - message='AnalyzeOrgPolicyGovernedAssetsResponse.GovernedIamPolicy', - ) - consolidated_policy: 'AnalyzerOrgPolicy' = proto.Field( - proto.MESSAGE, - number=3, - message='AnalyzerOrgPolicy', - ) - policy_bundle: MutableSequence['AnalyzerOrgPolicy'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='AnalyzerOrgPolicy', - ) - - @property - def raw_page(self): - return self - - governed_assets: MutableSequence[GovernedAsset] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=GovernedAsset, - ) - constraint: 'AnalyzerOrgPolicyConstraint' = proto.Field( - proto.MESSAGE, - number=2, - message='AnalyzerOrgPolicyConstraint', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py b/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py deleted file mode 100644 index e1a65567..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py +++ /dev/null @@ -1,1683 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore -from google.cloud.osconfig_v1.types import inventory -from google.iam.v1 import policy_pb2 # type: ignore -from google.identity.accesscontextmanager.v1 import access_level_pb2 # type: ignore -from google.identity.accesscontextmanager.v1 import access_policy_pb2 # type: ignore -from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import code_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1', - manifest={ - 'TemporalAsset', - 'TimeWindow', - 'Asset', - 'Resource', - 'RelatedAssets', - 'RelationshipAttributes', - 'RelatedAsset', - 'Tag', - 'EffectiveTagDetails', - 'ResourceSearchResult', - 'VersionedResource', - 'AttachedResource', - 'RelatedResources', - 'RelatedResource', - 'IamPolicySearchResult', - 'IamPolicyAnalysisState', - 'ConditionEvaluation', - 'IamPolicyAnalysisResult', - }, -) - - -class TemporalAsset(proto.Message): - r"""An asset in Google Cloud and its temporal metadata, including - the time window when it was observed and its status during that - window. - - Attributes: - window (google.cloud.asset_v1.types.TimeWindow): - The time window when the asset data and state - was observed. - deleted (bool): - Whether the asset has been deleted or not. - asset (google.cloud.asset_v1.types.Asset): - An asset in Google Cloud. - prior_asset_state (google.cloud.asset_v1.types.TemporalAsset.PriorAssetState): - State of prior_asset. - prior_asset (google.cloud.asset_v1.types.Asset): - Prior copy of the asset. Populated if prior_asset_state is - PRESENT. Currently this is only set for responses in - Real-Time Feed. - """ - class PriorAssetState(proto.Enum): - r"""State of prior asset. - - Values: - PRIOR_ASSET_STATE_UNSPECIFIED (0): - prior_asset is not applicable for the current asset. - PRESENT (1): - prior_asset is populated correctly. - INVALID (2): - Failed to set prior_asset. - DOES_NOT_EXIST (3): - Current asset is the first known state. - DELETED (4): - prior_asset is a deletion. - """ - PRIOR_ASSET_STATE_UNSPECIFIED = 0 - PRESENT = 1 - INVALID = 2 - DOES_NOT_EXIST = 3 - DELETED = 4 - - window: 'TimeWindow' = proto.Field( - proto.MESSAGE, - number=1, - message='TimeWindow', - ) - deleted: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset: 'Asset' = proto.Field( - proto.MESSAGE, - number=3, - message='Asset', - ) - prior_asset_state: PriorAssetState = proto.Field( - proto.ENUM, - number=4, - enum=PriorAssetState, - ) - prior_asset: 'Asset' = proto.Field( - proto.MESSAGE, - number=5, - message='Asset', - ) - - -class TimeWindow(proto.Message): - r"""A time window specified by its ``start_time`` and ``end_time``. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of the time window (exclusive). - end_time (google.protobuf.timestamp_pb2.Timestamp): - End time of the time window (inclusive). If - not specified, the current timestamp is used - instead. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class Asset(proto.Message): - r"""An asset in Google Cloud. An asset can be any resource in the Google - Cloud `resource - hierarchy `__, - a resource outside the Google Cloud resource hierarchy (such as - Google Kubernetes Engine clusters and objects), or a policy (e.g. - IAM policy), or a relationship (e.g. an INSTANCE_TO_INSTANCEGROUP - relationship). See `Supported asset - types `__ - for more information. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update timestamp of an asset. update_time is - updated when create/update/delete operation is performed. - name (str): - The full name of the asset. Example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`` - - See `Resource - names `__ - for more information. - asset_type (str): - The type of the asset. Example: - ``compute.googleapis.com/Disk`` - - See `Supported asset - types `__ - for more information. - resource (google.cloud.asset_v1.types.Resource): - A representation of the resource. - iam_policy (google.iam.v1.policy_pb2.Policy): - A representation of the IAM policy set on a Google Cloud - resource. There can be a maximum of one IAM policy set on - any given resource. In addition, IAM policies inherit their - granted access scope from any policies set on parent - resources in the resource hierarchy. Therefore, the - effectively policy is the union of both the policy set on - this resource and each policy set on all of the resource's - ancestry resource levels in the hierarchy. See `this - topic `__ - for more information. - org_policy (MutableSequence[google.cloud.orgpolicy.v1.orgpolicy_pb2.Policy]): - A representation of an `organization - policy `__. - There can be more than one organization policy with - different constraints set on a given resource. - access_policy (google.identity.accesscontextmanager.v1.access_policy_pb2.AccessPolicy): - Please also refer to the `access policy user - guide `__. - - This field is a member of `oneof`_ ``access_context_policy``. - access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): - Please also refer to the `access level user - guide `__. - - This field is a member of `oneof`_ ``access_context_policy``. - service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): - Please also refer to the `service perimeter user - guide `__. - - This field is a member of `oneof`_ ``access_context_policy``. - os_inventory (google.cloud.osconfig_v1.types.Inventory): - A representation of runtime OS Inventory information. See - `this - topic `__ - for more information. - related_assets (google.cloud.asset_v1.types.RelatedAssets): - DEPRECATED. This field only presents for the - purpose of backward-compatibility. The server - will never generate responses with this field. - The related assets of the asset of one - relationship type. One asset only represents one - type of relationship. - related_asset (google.cloud.asset_v1.types.RelatedAsset): - One related asset of the current asset. - ancestors (MutableSequence[str]): - The ancestry path of an asset in Google Cloud `resource - hierarchy `__, - represented as a list of relative resource names. An - ancestry path starts with the closest ancestor in the - hierarchy and ends at root. If the asset is a project, - folder, or organization, the ancestry path starts from the - asset itself. - - Example: - ``["projects/123456789", "folders/5432", "organizations/1234"]`` - """ - - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - name: str = proto.Field( - proto.STRING, - number=1, - ) - asset_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource: 'Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='Resource', - ) - iam_policy: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - org_policy: MutableSequence[orgpolicy_pb2.Policy] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=orgpolicy_pb2.Policy, - ) - access_policy: access_policy_pb2.AccessPolicy = proto.Field( - proto.MESSAGE, - number=7, - oneof='access_context_policy', - message=access_policy_pb2.AccessPolicy, - ) - access_level: access_level_pb2.AccessLevel = proto.Field( - proto.MESSAGE, - number=8, - oneof='access_context_policy', - message=access_level_pb2.AccessLevel, - ) - service_perimeter: service_perimeter_pb2.ServicePerimeter = proto.Field( - proto.MESSAGE, - number=9, - oneof='access_context_policy', - message=service_perimeter_pb2.ServicePerimeter, - ) - os_inventory: inventory.Inventory = proto.Field( - proto.MESSAGE, - number=12, - message=inventory.Inventory, - ) - related_assets: 'RelatedAssets' = proto.Field( - proto.MESSAGE, - number=13, - message='RelatedAssets', - ) - related_asset: 'RelatedAsset' = proto.Field( - proto.MESSAGE, - number=15, - message='RelatedAsset', - ) - ancestors: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - - -class Resource(proto.Message): - r"""A representation of a Google Cloud resource. - - Attributes: - version (str): - The API version. Example: ``v1`` - discovery_document_uri (str): - The URL of the discovery document containing the resource's - JSON schema. Example: - ``https://www.googleapis.com/discovery/v1/apis/compute/v1/rest`` - - This value is unspecified for resources that do not have an - API based on a discovery document, such as Cloud Bigtable. - discovery_name (str): - The JSON schema name listed in the discovery document. - Example: ``Project`` - - This value is unspecified for resources that do not have an - API based on a discovery document, such as Cloud Bigtable. - resource_url (str): - The REST URL for accessing the resource. An HTTP ``GET`` - request using this URL returns the resource itself. Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`` - - This value is unspecified for resources without a REST API. - parent (str): - The full name of the immediate parent of this resource. See - `Resource - Names `__ - for more information. - - For Google Cloud assets, this value is the parent resource - defined in the `IAM policy - hierarchy `__. - Example: - ``//cloudresourcemanager.googleapis.com/projects/my_project_123`` - - For third-party assets, this field may be set differently. - data (google.protobuf.struct_pb2.Struct): - The content of the resource, in which some - sensitive fields are removed and may not be - present. - location (str): - The location of the resource in Google Cloud, - such as its zone and region. For more - information, see - https://cloud.google.com/about/locations/. - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - discovery_document_uri: str = proto.Field( - proto.STRING, - number=2, - ) - discovery_name: str = proto.Field( - proto.STRING, - number=3, - ) - resource_url: str = proto.Field( - proto.STRING, - number=4, - ) - parent: str = proto.Field( - proto.STRING, - number=5, - ) - data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - location: str = proto.Field( - proto.STRING, - number=8, - ) - - -class RelatedAssets(proto.Message): - r"""DEPRECATED. This message only presents for the purpose of - backward-compatibility. The server will never populate this message - in responses. The detailed related assets with the - ``relationship_type``. - - Attributes: - relationship_attributes (google.cloud.asset_v1.types.RelationshipAttributes): - The detailed relationship attributes. - assets (MutableSequence[google.cloud.asset_v1.types.RelatedAsset]): - The peer resources of the relationship. - """ - - relationship_attributes: 'RelationshipAttributes' = proto.Field( - proto.MESSAGE, - number=1, - message='RelationshipAttributes', - ) - assets: MutableSequence['RelatedAsset'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='RelatedAsset', - ) - - -class RelationshipAttributes(proto.Message): - r"""DEPRECATED. This message only presents for the purpose of - backward-compatibility. The server will never populate this message - in responses. The relationship attributes which include ``type``, - ``source_resource_type``, ``target_resource_type`` and ``action``. - - Attributes: - type_ (str): - The unique identifier of the relationship type. Example: - ``INSTANCE_TO_INSTANCEGROUP`` - source_resource_type (str): - The source asset type. Example: - ``compute.googleapis.com/Instance`` - target_resource_type (str): - The target asset type. Example: - ``compute.googleapis.com/Disk`` - action (str): - The detail of the relationship, e.g. ``contains``, - ``attaches`` - """ - - type_: str = proto.Field( - proto.STRING, - number=4, - ) - source_resource_type: str = proto.Field( - proto.STRING, - number=1, - ) - target_resource_type: str = proto.Field( - proto.STRING, - number=2, - ) - action: str = proto.Field( - proto.STRING, - number=3, - ) - - -class RelatedAsset(proto.Message): - r"""An asset identifier in Google Cloud which contains its name, type - and ancestors. An asset can be any resource in the Google Cloud - `resource - hierarchy `__, - a resource outside the Google Cloud resource hierarchy (such as - Google Kubernetes Engine clusters and objects), or a policy (e.g. - IAM policy). See `Supported asset - types `__ - for more information. - - Attributes: - asset (str): - The full name of the asset. Example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`` - - See `Resource - names `__ - for more information. - asset_type (str): - The type of the asset. Example: - ``compute.googleapis.com/Disk`` - - See `Supported asset - types `__ - for more information. - ancestors (MutableSequence[str]): - The ancestors of an asset in Google Cloud `resource - hierarchy `__, - represented as a list of relative resource names. An - ancestry path starts with the closest ancestor in the - hierarchy and ends at root. - - Example: - ``["projects/123456789", "folders/5432", "organizations/1234"]`` - relationship_type (str): - The unique identifier of the relationship type. Example: - ``INSTANCE_TO_INSTANCEGROUP`` - """ - - asset: str = proto.Field( - proto.STRING, - number=1, - ) - asset_type: str = proto.Field( - proto.STRING, - number=2, - ) - ancestors: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - relationship_type: str = proto.Field( - proto.STRING, - number=4, - ) - - -class Tag(proto.Message): - r"""The key and value for a - `tag `__, - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - tag_key (str): - TagKey namespaced name, in the format of - {ORG_ID}/{TAG_KEY_SHORT_NAME}. - - This field is a member of `oneof`_ ``_tag_key``. - tag_value (str): - TagValue namespaced name, in the format of - {ORG_ID}/{TAG_KEY_SHORT_NAME}/{TAG_VALUE_SHORT_NAME}. - - This field is a member of `oneof`_ ``_tag_value``. - tag_value_id (str): - TagValue ID, in the format of tagValues/{TAG_VALUE_ID}. - - This field is a member of `oneof`_ ``_tag_value_id``. - """ - - tag_key: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - tag_value: str = proto.Field( - proto.STRING, - number=3, - optional=True, - ) - tag_value_id: str = proto.Field( - proto.STRING, - number=4, - optional=True, - ) - - -class EffectiveTagDetails(proto.Message): - r"""The effective tags and the ancestor resources from which they - were inherited. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - attached_resource (str): - The `full resource - name `__ - of the ancestor from which an [effective_tag][] is - inherited, according to `tag - inheritance `__. - - This field is a member of `oneof`_ ``_attached_resource``. - effective_tags (MutableSequence[google.cloud.asset_v1.types.Tag]): - The effective tags inherited from the - [attached_resource][google.cloud.asset.v1.EffectiveTagDetails.attached_resource]. - Note that tags with the same key but different values may - attach to resources at a different hierarchy levels. The - lower hierarchy tag value will overwrite the higher - hierarchy tag value of the same tag key. In this case, the - tag value at the higher hierarchy level will be removed. For - more information, see `tag - inheritance `__. - """ - - attached_resource: str = proto.Field( - proto.STRING, - number=1, - optional=True, - ) - effective_tags: MutableSequence['Tag'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='Tag', - ) - - -class ResourceSearchResult(proto.Message): - r"""A result of Resource Search, containing information of a - cloud resource. Next ID: 34 - - Attributes: - name (str): - The full resource name of this resource. Example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Cloud Asset Inventory Resource Name - Format `__ - for more information. - - To search against the ``name``: - - - Use a field query. Example: ``name:instance1`` - - Use a free text query. Example: ``instance1`` - asset_type (str): - The type of this resource. Example: - ``compute.googleapis.com/Disk``. - - To search against the ``asset_type``: - - - Specify the ``asset_type`` field in your search request. - project (str): - The project that this resource belongs to, in the form of - projects/{PROJECT_NUMBER}. This field is available when the - resource belongs to a project. - - To search against ``project``: - - - Use a field query. Example: ``project:12345`` - - Use a free text query. Example: ``12345`` - - Specify the ``scope`` field as this project in your - search request. - folders (MutableSequence[str]): - The folder(s) that this resource belongs to, in the form of - folders/{FOLDER_NUMBER}. This field is available when the - resource belongs to one or more folders. - - To search against ``folders``: - - - Use a field query. Example: ``folders:(123 OR 456)`` - - Use a free text query. Example: ``123`` - - Specify the ``scope`` field as this folder in your search - request. - organization (str): - The organization that this resource belongs to, in the form - of organizations/{ORGANIZATION_NUMBER}. This field is - available when the resource belongs to an organization. - - To search against ``organization``: - - - Use a field query. Example: ``organization:123`` - - Use a free text query. Example: ``123`` - - Specify the ``scope`` field as this organization in your - search request. - display_name (str): - The display name of this resource. This field is available - only when the resource's Protobuf contains it. - - To search against the ``display_name``: - - - Use a field query. Example: ``displayName:"My Instance"`` - - Use a free text query. Example: ``"My Instance"`` - description (str): - One or more paragraphs of text description of this resource. - Maximum length could be up to 1M bytes. This field is - available only when the resource's Protobuf contains it. - - To search against the ``description``: - - - Use a field query. Example: - ``description:"important instance"`` - - Use a free text query. Example: ``"important instance"`` - location (str): - Location can be ``global``, regional like ``us-east1``, or - zonal like ``us-west1-b``. This field is available only when - the resource's Protobuf contains it. - - To search against the ``location``: - - - Use a field query. Example: ``location:us-west*`` - - Use a free text query. Example: ``us-west*`` - labels (MutableMapping[str, str]): - Labels associated with this resource. See `Labelling and - grouping Google Cloud - resources `__ - for more information. This field is available only when the - resource's Protobuf contains it. - - To search against the ``labels``: - - - Use a field query: - - - query on any label's key or value. Example: - ``labels:prod`` - - query by a given label. Example: ``labels.env:prod`` - - query by a given label's existence. Example: - ``labels.env:*`` - - - Use a free text query. Example: ``prod`` - network_tags (MutableSequence[str]): - Network tags associated with this resource. Like labels, - network tags are a type of annotations used to group Google - Cloud resources. See `Labelling Google Cloud - resources `__ - for more information. This field is available only when the - resource's Protobuf contains it. - - To search against the ``network_tags``: - - - Use a field query. Example: ``networkTags:internal`` - - Use a free text query. Example: ``internal`` - kms_key (str): - The Cloud KMS - `CryptoKey `__ - name or - `CryptoKeyVersion `__ - name. - - This field only presents for the purpose of backward - compatibility. Please use the ``kms_keys`` field to retrieve - Cloud KMS key information. This field is available only when - the resource's Protobuf contains it and will only be - populated for `these resource - types `__ - for backward compatible purposes. - - To search against the ``kms_key``: - - - Use a field query. Example: ``kmsKey:key`` - - Use a free text query. Example: ``key`` - kms_keys (MutableSequence[str]): - The Cloud KMS - `CryptoKey `__ - names or - `CryptoKeyVersion `__ - names. This field is available only when the resource's - Protobuf contains it. - - To search against the ``kms_keys``: - - - Use a field query. Example: ``kmsKeys:key`` - - Use a free text query. Example: ``key`` - create_time (google.protobuf.timestamp_pb2.Timestamp): - The create timestamp of this resource, at which the resource - was created. The granularity is in seconds. Timestamp.nanos - will always be 0. This field is available only when the - resource's Protobuf contains it. - - To search against ``create_time``: - - - Use a field query. - - - value in seconds since unix epoch. Example: - ``createTime > 1609459200`` - - value in date string. Example: - ``createTime > 2021-01-01`` - - value in date-time string (must be quoted). Example: - ``createTime > "2021-01-01T00:00:00"`` - update_time (google.protobuf.timestamp_pb2.Timestamp): - The last update timestamp of this resource, at which the - resource was last modified or deleted. The granularity is in - seconds. Timestamp.nanos will always be 0. This field is - available only when the resource's Protobuf contains it. - - To search against ``update_time``: - - - Use a field query. - - - value in seconds since unix epoch. Example: - ``updateTime < 1609459200`` - - value in date string. Example: - ``updateTime < 2021-01-01`` - - value in date-time string (must be quoted). Example: - ``updateTime < "2021-01-01T00:00:00"`` - state (str): - The state of this resource. Different resources types have - different state definitions that are mapped from various - fields of different resource types. This field is available - only when the resource's Protobuf contains it. - - Example: If the resource is an instance provided by Compute - Engine, its state will include PROVISIONING, STAGING, - RUNNING, STOPPING, SUSPENDING, SUSPENDED, REPAIRING, and - TERMINATED. See ``status`` definition in `API - Reference `__. - If the resource is a project provided by Resource Manager, - its state will include LIFECYCLE_STATE_UNSPECIFIED, ACTIVE, - DELETE_REQUESTED and DELETE_IN_PROGRESS. See - ``lifecycleState`` definition in `API - Reference `__. - - To search against the ``state``: - - - Use a field query. Example: ``state:RUNNING`` - - Use a free text query. Example: ``RUNNING`` - additional_attributes (google.protobuf.struct_pb2.Struct): - The additional searchable attributes of this resource. The - attributes may vary from one resource type to another. - Examples: ``projectId`` for Project, ``dnsName`` for DNS - ManagedZone. This field contains a subset of the resource - metadata fields that are returned by the List or Get APIs - provided by the corresponding Google Cloud service (e.g., - Compute Engine). see `API references and supported - searchable - attributes `__ - to see which fields are included. - - You can search values of these fields through free text - search. However, you should not consume the field - programically as the field names and values may change as - the Google Cloud service updates to a new incompatible API - version. - - To search against the ``additional_attributes``: - - - Use a free text query to match the attributes values. - Example: to search - ``additional_attributes = { dnsName: "foobar" }``, you - can issue a query ``foobar``. - parent_full_resource_name (str): - The full resource name of this resource's parent, if it has - one. To search against the ``parent_full_resource_name``: - - - Use a field query. Example: - ``parentFullResourceName:"project-name"`` - - Use a free text query. Example: ``project-name`` - versioned_resources (MutableSequence[google.cloud.asset_v1.types.VersionedResource]): - Versioned resource representations of this resource. This is - repeated because there could be multiple versions of - resource representations during version migration. - - This ``versioned_resources`` field is not searchable. Some - attributes of the resource representations are exposed in - ``additional_attributes`` field, so as to allow users to - search on them. - attached_resources (MutableSequence[google.cloud.asset_v1.types.AttachedResource]): - Attached resources of this resource. For example, an - OSConfig Inventory is an attached resource of a Compute - Instance. This field is repeated because a resource could - have multiple attached resources. - - This ``attached_resources`` field is not searchable. Some - attributes of the attached resources are exposed in - ``additional_attributes`` field, so as to allow users to - search on them. - relationships (MutableMapping[str, google.cloud.asset_v1.types.RelatedResources]): - A map of related resources of this resource, keyed by the - relationship type. A relationship type is in the format of - {SourceType}*{ACTION}*\ {DestType}. Example: - ``DISK_TO_INSTANCE``, ``DISK_TO_NETWORK``, - ``INSTANCE_TO_INSTANCEGROUP``. See `supported relationship - types `__. - tag_keys (MutableSequence[str]): - This field is only present for the purpose of backward - compatibility. Please use the ``tags`` field instead. - - TagKey namespaced names, in the format of - {ORG_ID}/{TAG_KEY_SHORT_NAME}. To search against the - ``tagKeys``: - - - Use a field query. Example: - - - ``tagKeys:"123456789/env*"`` - - ``tagKeys="123456789/env"`` - - ``tagKeys:"env"`` - - - Use a free text query. Example: - - - ``env`` - tag_values (MutableSequence[str]): - This field is only present for the purpose of backward - compatibility. Please use the ``tags`` field instead. - - TagValue namespaced names, in the format of - {ORG_ID}/{TAG_KEY_SHORT_NAME}/{TAG_VALUE_SHORT_NAME}. To - search against the ``tagValues``: - - - Use a field query. Example: - - - ``tagValues:"env"`` - - ``tagValues:"env/prod"`` - - ``tagValues:"123456789/env/prod*"`` - - ``tagValues="123456789/env/prod"`` - - - Use a free text query. Example: - - - ``prod`` - tag_value_ids (MutableSequence[str]): - This field is only present for the purpose of backward - compatibility. Please use the ``tags`` field instead. - - TagValue IDs, in the format of tagValues/{TAG_VALUE_ID}. To - search against the ``tagValueIds``: - - - Use a field query. Example: - - - ``tagValueIds="tagValues/456"`` - - - Use a free text query. Example: - - - ``456`` - tags (MutableSequence[google.cloud.asset_v1.types.Tag]): - The tags directly attached to this resource. - - To search against the ``tags``: - - - Use a field query. Example: - - - ``tagKeys:"123456789/env*"`` - - ``tagKeys="123456789/env"`` - - ``tagKeys:"env"`` - - ``tagValues:"env"`` - - ``tagValues:"env/prod"`` - - ``tagValues:"123456789/env/prod*"`` - - ``tagValues="123456789/env/prod"`` - - ``tagValueIds="tagValues/456"`` - - - Use a free text query. Example: - - - ``env/prod`` - effective_tags (MutableSequence[google.cloud.asset_v1.types.EffectiveTagDetails]): - The effective tags on this resource. All of the tags that - are both attached to and inherited by a resource are - collectively called the effective tags. For more - information, see `tag - inheritance `__. - - To search against the ``effective_tags``: - - - Use a field query. Example: - - - ``effectiveTagKeys:"123456789/env*"`` - - ``effectiveTagKeys="123456789/env"`` - - ``effectiveTagKeys:"env"`` - - ``effectiveTagValues:"env"`` - - ``effectiveTagValues:"env/prod"`` - - ``effectiveTagValues:"123456789/env/prod*"`` - - ``effectiveTagValues="123456789/env/prod"`` - - ``effectiveTagValueIds="tagValues/456"`` - parent_asset_type (str): - The type of this resource's immediate parent, if there is - one. - - To search against the ``parent_asset_type``: - - - Use a field query. Example: - ``parentAssetType:"cloudresourcemanager.googleapis.com/Project"`` - - Use a free text query. Example: - ``cloudresourcemanager.googleapis.com/Project`` - scc_security_marks (MutableMapping[str, str]): - The actual content of Security Command Center security marks - associated with the asset. - - Note that both staging & prod SecurityMarks are attached on - prod resources. In CAS preprod/prod, both staging & prod - SecurityMarks are ingested and returned in the following - ``security_marks`` map. In that case, the prefix "staging." - will be added to the keys of all the staging marks. To - search against SCC SecurityMarks field: - - - Use a field query: - - - query by a given key value pair. Example: - ``sccSecurityMarks.foo=bar`` - - query by a given key's existence. Example: - ``sccSecurityMarks.foo:*`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - asset_type: str = proto.Field( - proto.STRING, - number=2, - ) - project: str = proto.Field( - proto.STRING, - number=3, - ) - folders: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=17, - ) - organization: str = proto.Field( - proto.STRING, - number=18, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - location: str = proto.Field( - proto.STRING, - number=6, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - network_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=8, - ) - kms_key: str = proto.Field( - proto.STRING, - number=10, - ) - kms_keys: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=28, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - state: str = proto.Field( - proto.STRING, - number=13, - ) - additional_attributes: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - parent_full_resource_name: str = proto.Field( - proto.STRING, - number=19, - ) - versioned_resources: MutableSequence['VersionedResource'] = proto.RepeatedField( - proto.MESSAGE, - number=16, - message='VersionedResource', - ) - attached_resources: MutableSequence['AttachedResource'] = proto.RepeatedField( - proto.MESSAGE, - number=20, - message='AttachedResource', - ) - relationships: MutableMapping[str, 'RelatedResources'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=21, - message='RelatedResources', - ) - tag_keys: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=23, - ) - tag_values: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=25, - ) - tag_value_ids: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=26, - ) - tags: MutableSequence['Tag'] = proto.RepeatedField( - proto.MESSAGE, - number=29, - message='Tag', - ) - effective_tags: MutableSequence['EffectiveTagDetails'] = proto.RepeatedField( - proto.MESSAGE, - number=30, - message='EffectiveTagDetails', - ) - parent_asset_type: str = proto.Field( - proto.STRING, - number=103, - ) - scc_security_marks: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=32, - ) - - -class VersionedResource(proto.Message): - r"""Resource representation as defined by the corresponding - service providing the resource for a given API version. - - Attributes: - version (str): - API version of the resource. - - Example: If the resource is an instance provided by Compute - Engine v1 API as defined in - ``https://cloud.google.com/compute/docs/reference/rest/v1/instances``, - version will be "v1". - resource (google.protobuf.struct_pb2.Struct): - JSON representation of the resource as defined by the - corresponding service providing this resource. - - Example: If the resource is an instance provided by Compute - Engine, this field will contain the JSON representation of - the instance as defined by Compute Engine: - ``https://cloud.google.com/compute/docs/reference/rest/v1/instances``. - - You can find the resource definition for each supported - resource type in this table: - ``https://cloud.google.com/asset-inventory/docs/supported-asset-types#searchable_asset_types`` - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - resource: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=2, - message=struct_pb2.Struct, - ) - - -class AttachedResource(proto.Message): - r"""Attached resource representation, which is defined by the - corresponding service provider. It represents an attached - resource's payload. - - Attributes: - asset_type (str): - The type of this attached resource. - - Example: ``osconfig.googleapis.com/Inventory`` - - You can find the supported attached asset types of each - resource in this table: - ``https://cloud.google.com/asset-inventory/docs/supported-asset-types#searchable_asset_types`` - versioned_resources (MutableSequence[google.cloud.asset_v1.types.VersionedResource]): - Versioned resource representations of this - attached resource. This is repeated because - there could be multiple versions of the attached - resource representations during version - migration. - """ - - asset_type: str = proto.Field( - proto.STRING, - number=1, - ) - versioned_resources: MutableSequence['VersionedResource'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='VersionedResource', - ) - - -class RelatedResources(proto.Message): - r"""The related resources of the primary resource. - - Attributes: - related_resources (MutableSequence[google.cloud.asset_v1.types.RelatedResource]): - The detailed related resources of the primary - resource. - """ - - related_resources: MutableSequence['RelatedResource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='RelatedResource', - ) - - -class RelatedResource(proto.Message): - r"""The detailed related resource. - - Attributes: - asset_type (str): - The type of the asset. Example: - ``compute.googleapis.com/Instance`` - full_resource_name (str): - The full resource name of the related resource. Example: - ``//compute.googleapis.com/projects/my_proj_123/zones/instance/instance123`` - """ - - asset_type: str = proto.Field( - proto.STRING, - number=1, - ) - full_resource_name: str = proto.Field( - proto.STRING, - number=2, - ) - - -class IamPolicySearchResult(proto.Message): - r"""A result of IAM Policy search, containing information of an - IAM policy. - - Attributes: - resource (str): - The full resource name of the resource associated with this - IAM policy. Example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Cloud Asset Inventory Resource Name - Format `__ - for more information. - - To search against the ``resource``: - - - use a field query. Example: - ``resource:organizations/123`` - asset_type (str): - The type of the resource associated with this IAM policy. - Example: ``compute.googleapis.com/Disk``. - - To search against the ``asset_type``: - - - specify the ``asset_types`` field in your search request. - project (str): - The project that the associated Google Cloud resource - belongs to, in the form of projects/{PROJECT_NUMBER}. If an - IAM policy is set on a resource (like VM instance, Cloud - Storage bucket), the project field will indicate the project - that contains the resource. If an IAM policy is set on a - folder or orgnization, this field will be empty. - - To search against the ``project``: - - - specify the ``scope`` field as this project in your - search request. - folders (MutableSequence[str]): - The folder(s) that the IAM policy belongs to, in the form of - folders/{FOLDER_NUMBER}. This field is available when the - IAM policy belongs to one or more folders. - - To search against ``folders``: - - - use a field query. Example: ``folders:(123 OR 456)`` - - use a free text query. Example: ``123`` - - specify the ``scope`` field as this folder in your search - request. - organization (str): - The organization that the IAM policy belongs to, in the form - of organizations/{ORGANIZATION_NUMBER}. This field is - available when the IAM policy belongs to an organization. - - To search against ``organization``: - - - use a field query. Example: ``organization:123`` - - use a free text query. Example: ``123`` - - specify the ``scope`` field as this organization in your - search request. - policy (google.iam.v1.policy_pb2.Policy): - The IAM policy directly set on the given resource. Note that - the original IAM policy can contain multiple bindings. This - only contains the bindings that match the given query. For - queries that don't contain a constrain on policies (e.g., an - empty query), this contains all the bindings. - - To search against the ``policy`` bindings: - - - use a field query: - - - query by the policy contained members. Example: - ``policy:amy@gmail.com`` - - query by the policy contained roles. Example: - ``policy:roles/compute.admin`` - - query by the policy contained roles' included - permissions. Example: - ``policy.role.permissions:compute.instances.create`` - explanation (google.cloud.asset_v1.types.IamPolicySearchResult.Explanation): - Explanation about the IAM policy search - result. It contains additional information to - explain why the search result matches the query. - """ - - class Explanation(proto.Message): - r"""Explanation about the IAM policy search result. - - Attributes: - matched_permissions (MutableMapping[str, google.cloud.asset_v1.types.IamPolicySearchResult.Explanation.Permissions]): - The map from roles to their included permissions that match - the permission query (i.e., a query containing - ``policy.role.permissions:``). Example: if query - ``policy.role.permissions:compute.disk.get`` matches a - policy binding that contains owner role, the - matched_permissions will be - ``{"roles/owner": ["compute.disk.get"]}``. The roles can - also be found in the returned ``policy`` bindings. Note that - the map is populated only for requests with permission - queries. - """ - - class Permissions(proto.Message): - r"""IAM permissions - - Attributes: - permissions (MutableSequence[str]): - A list of permissions. A sample permission string: - ``compute.disk.get``. - """ - - permissions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - matched_permissions: MutableMapping[str, 'IamPolicySearchResult.Explanation.Permissions'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='IamPolicySearchResult.Explanation.Permissions', - ) - - resource: str = proto.Field( - proto.STRING, - number=1, - ) - asset_type: str = proto.Field( - proto.STRING, - number=5, - ) - project: str = proto.Field( - proto.STRING, - number=2, - ) - folders: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - organization: str = proto.Field( - proto.STRING, - number=7, - ) - policy: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=3, - message=policy_pb2.Policy, - ) - explanation: Explanation = proto.Field( - proto.MESSAGE, - number=4, - message=Explanation, - ) - - -class IamPolicyAnalysisState(proto.Message): - r"""Represents the detailed state of an entity under analysis, - such as a resource, an identity or an access. - - Attributes: - code (google.rpc.code_pb2.Code): - The Google standard error code that best describes the - state. For example: - - - OK means the analysis on this entity has been - successfully finished; - - PERMISSION_DENIED means an access denied error is - encountered; - - DEADLINE_EXCEEDED means the analysis on this entity - hasn't been started in time; - cause (str): - The human-readable description of the cause - of failure. - """ - - code: code_pb2.Code = proto.Field( - proto.ENUM, - number=1, - enum=code_pb2.Code, - ) - cause: str = proto.Field( - proto.STRING, - number=2, - ) - - -class ConditionEvaluation(proto.Message): - r"""The Condition evaluation. - - Attributes: - evaluation_value (google.cloud.asset_v1.types.ConditionEvaluation.EvaluationValue): - The evaluation result. - """ - class EvaluationValue(proto.Enum): - r"""Value of this expression. - - Values: - EVALUATION_VALUE_UNSPECIFIED (0): - Reserved for future use. - TRUE (1): - The evaluation result is ``true``. - FALSE (2): - The evaluation result is ``false``. - CONDITIONAL (3): - The evaluation result is ``conditional`` when the condition - expression contains variables that are either missing input - values or have not been supported by Analyzer yet. - """ - EVALUATION_VALUE_UNSPECIFIED = 0 - TRUE = 1 - FALSE = 2 - CONDITIONAL = 3 - - evaluation_value: EvaluationValue = proto.Field( - proto.ENUM, - number=1, - enum=EvaluationValue, - ) - - -class IamPolicyAnalysisResult(proto.Message): - r"""IAM Policy analysis result, consisting of one IAM policy - binding and derived access control lists. - - Attributes: - attached_resource_full_name (str): - The `full resource - name `__ - of the resource to which the - [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] - policy attaches. - iam_binding (google.iam.v1.policy_pb2.Binding): - The IAM policy binding under analysis. - access_control_lists (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.AccessControlList]): - The access control lists derived from the - [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] - that match or potentially match resource and access - selectors specified in the request. - identity_list (google.cloud.asset_v1.types.IamPolicyAnalysisResult.IdentityList): - The identity list derived from members of the - [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] - that match or potentially match identity selector specified - in the request. - fully_explored (bool): - Represents whether all analyses on the - [iam_binding][google.cloud.asset.v1.IamPolicyAnalysisResult.iam_binding] - have successfully finished. - """ - - class Resource(proto.Message): - r"""A Google Cloud resource under analysis. - - Attributes: - full_resource_name (str): - The `full resource - name `__ - analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): - The analysis state of this resource. - """ - - full_resource_name: str = proto.Field( - proto.STRING, - number=1, - ) - analysis_state: 'IamPolicyAnalysisState' = proto.Field( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisState', - ) - - class Access(proto.Message): - r"""An IAM role or permission under analysis. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - role (str): - The role. - - This field is a member of `oneof`_ ``oneof_access``. - permission (str): - The permission. - - This field is a member of `oneof`_ ``oneof_access``. - analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): - The analysis state of this access. - """ - - role: str = proto.Field( - proto.STRING, - number=1, - oneof='oneof_access', - ) - permission: str = proto.Field( - proto.STRING, - number=2, - oneof='oneof_access', - ) - analysis_state: 'IamPolicyAnalysisState' = proto.Field( - proto.MESSAGE, - number=3, - message='IamPolicyAnalysisState', - ) - - class Identity(proto.Message): - r"""An identity under analysis. - - Attributes: - name (str): - The identity of members, formatted as appear in an `IAM - policy - binding `__. - For example, they might be formatted like the following: - - - user:foo@google.com - - group:group1@google.com - - serviceAccount:s1@prj1.iam.gserviceaccount.com - - projectOwner:some_project_id - - domain:google.com - - allUsers - analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): - The analysis state of this identity. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - analysis_state: 'IamPolicyAnalysisState' = proto.Field( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisState', - ) - - class Edge(proto.Message): - r"""A directional edge. - - Attributes: - source_node (str): - The source node of the edge. For example, it - could be a full resource name for a resource - node or an email of an identity. - target_node (str): - The target node of the edge. For example, it - could be a full resource name for a resource - node or an email of an identity. - """ - - source_node: str = proto.Field( - proto.STRING, - number=1, - ) - target_node: str = proto.Field( - proto.STRING, - number=2, - ) - - class AccessControlList(proto.Message): - r"""An access control list, derived from the above IAM policy binding, - which contains a set of resources and accesses. May include one item - from each set to compose an access control entry. - - NOTICE that there could be multiple access control lists for one IAM - policy binding. The access control lists are created based on - resource and access combinations. - - For example, assume we have the following cases in one IAM policy - binding: - - - Permission P1 and P2 apply to resource R1 and R2; - - Permission P3 applies to resource R2 and R3; - - This will result in the following access control lists: - - - AccessControlList 1: [R1, R2], [P1, P2] - - AccessControlList 2: [R2, R3], [P3] - - Attributes: - resources (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Resource]): - The resources that match one of the following conditions: - - - The resource_selector, if it is specified in request; - - Otherwise, resources reachable from the policy attached - resource. - accesses (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Access]): - The accesses that match one of the following conditions: - - - The access_selector, if it is specified in request; - - Otherwise, access specifiers reachable from the policy - binding's role. - resource_edges (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Edge]): - Resource edges of the graph starting from the policy - attached resource to any descendant resources. The - [Edge.source_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.source_node] - contains the full resource name of a parent resource and - [Edge.target_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.target_node] - contains the full resource name of a child resource. This - field is present only if the output_resource_edges option is - enabled in request. - condition_evaluation (google.cloud.asset_v1.types.ConditionEvaluation): - Condition evaluation for this - AccessControlList, if there is a condition - defined in the above IAM policy binding. - """ - - resources: MutableSequence['IamPolicyAnalysisResult.Resource'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisResult.Resource', - ) - accesses: MutableSequence['IamPolicyAnalysisResult.Access'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.Access', - ) - resource_edges: MutableSequence['IamPolicyAnalysisResult.Edge'] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='IamPolicyAnalysisResult.Edge', - ) - condition_evaluation: 'ConditionEvaluation' = proto.Field( - proto.MESSAGE, - number=4, - message='ConditionEvaluation', - ) - - class IdentityList(proto.Message): - r"""The identities and group edges. - - Attributes: - identities (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Identity]): - Only the identities that match one of the following - conditions will be presented: - - - The identity_selector, if it is specified in request; - - Otherwise, identities reachable from the policy binding's - members. - group_edges (MutableSequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Edge]): - Group identity edges of the graph starting from the - binding's group members to any node of the - [identities][google.cloud.asset.v1.IamPolicyAnalysisResult.IdentityList.identities]. - The - [Edge.source_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.source_node] - contains a group, such as ``group:parent@google.com``. The - [Edge.target_node][google.cloud.asset.v1.IamPolicyAnalysisResult.Edge.target_node] - contains a member of the group, such as - ``group:child@google.com`` or ``user:foo@google.com``. This - field is present only if the output_group_edges option is - enabled in request. - """ - - identities: MutableSequence['IamPolicyAnalysisResult.Identity'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisResult.Identity', - ) - group_edges: MutableSequence['IamPolicyAnalysisResult.Edge'] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.Edge', - ) - - attached_resource_full_name: str = proto.Field( - proto.STRING, - number=1, - ) - iam_binding: policy_pb2.Binding = proto.Field( - proto.MESSAGE, - number=2, - message=policy_pb2.Binding, - ) - access_control_lists: MutableSequence[AccessControlList] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AccessControlList, - ) - identity_list: IdentityList = proto.Field( - proto.MESSAGE, - number=4, - message=IdentityList, - ) - fully_explored: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -__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 574c5aed..00000000 --- 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 c333de24..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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/asset_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==7.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/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py deleted file mode 100644 index 4a13b281..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeIamPolicy -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_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 asset_v1 - - -async def sample_analyze_iam_policy(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - request = asset_v1.AnalyzeIamPolicyRequest( - analysis_query=analysis_query, - ) - - # Make the request - response = await client.analyze_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py deleted file mode 100644 index 47fb7196..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeIamPolicyLongrunning -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_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 asset_v1 - - -async def sample_analyze_iam_policy_longrunning(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - output_config = asset_v1.IamPolicyAnalysisOutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.AnalyzeIamPolicyLongrunningRequest( - analysis_query=analysis_query, - output_config=output_config, - ) - - # Make the request - operation = client.analyze_iam_policy_longrunning(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py deleted file mode 100644 index 5f29caec..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py +++ /dev/null @@ -1,63 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeIamPolicyLongrunning -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_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 asset_v1 - - -def sample_analyze_iam_policy_longrunning(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - output_config = asset_v1.IamPolicyAnalysisOutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.AnalyzeIamPolicyLongrunningRequest( - analysis_query=analysis_query, - output_config=output_config, - ) - - # Make the request - operation = client.analyze_iam_policy_longrunning(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py deleted file mode 100644 index c2aa7028..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeIamPolicy -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_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 asset_v1 - - -def sample_analyze_iam_policy(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - analysis_query = asset_v1.IamPolicyAnalysisQuery() - analysis_query.scope = "scope_value" - - request = asset_v1.AnalyzeIamPolicyRequest( - analysis_query=analysis_query, - ) - - # Make the request - response = client.analyze_iam_policy(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py deleted file mode 100644 index 377f2e12..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeMove -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeMove_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 asset_v1 - - -async def sample_analyze_move(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeMoveRequest( - resource="resource_value", - destination_parent="destination_parent_value", - ) - - # Make the request - response = await client.analyze_move(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeMove_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py deleted file mode 100644 index 5ec453c1..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_move_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeMove -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeMove_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 asset_v1 - - -def sample_analyze_move(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeMoveRequest( - resource="resource_value", - destination_parent="destination_parent_value", - ) - - # Make the request - response = client.analyze_move(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeMove_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py deleted file mode 100644 index 625f3dec..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeOrgPolicies -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_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 asset_v1 - - -async def sample_analyze_org_policies(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPoliciesRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py deleted file mode 100644 index 892f5a15..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeOrgPolicies -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_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 asset_v1 - - -def sample_analyze_org_policies(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPoliciesRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py deleted file mode 100644 index 81b67efb..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeOrgPolicyGovernedAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_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 asset_v1 - - -async def sample_analyze_org_policy_governed_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py deleted file mode 100644 index 86aca87d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeOrgPolicyGovernedAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_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 asset_v1 - - -def sample_analyze_org_policy_governed_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedAssetsRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py deleted file mode 100644 index 3a24500e..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeOrgPolicyGovernedContainers -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_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 asset_v1 - - -async def sample_analyze_org_policy_governed_containers(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_containers(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py deleted file mode 100644 index 4aa243c9..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AnalyzeOrgPolicyGovernedContainers -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_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 asset_v1 - - -def sample_analyze_org_policy_governed_containers(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.AnalyzeOrgPolicyGovernedContainersRequest( - scope="scope_value", - constraint="constraint_value", - ) - - # Make the request - page_result = client.analyze_org_policy_governed_containers(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py deleted file mode 100644 index 6dd1e1dc..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchGetAssetsHistory -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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 asset_v1 - - -async def sample_batch_get_assets_history(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetAssetsHistoryRequest( - parent="parent_value", - ) - - # Make the request - response = await client.batch_get_assets_history(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py deleted file mode 100644 index 87e233fb..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchGetAssetsHistory -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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 asset_v1 - - -def sample_batch_get_assets_history(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetAssetsHistoryRequest( - parent="parent_value", - ) - - # Make the request - response = client.batch_get_assets_history(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py deleted file mode 100644 index 30ef0c4e..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchGetEffectiveIamPolicies -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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 asset_v1 - - -async def sample_batch_get_effective_iam_policies(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetEffectiveIamPoliciesRequest( - scope="scope_value", - names=['names_value1', 'names_value2'], - ) - - # Make the request - response = await client.batch_get_effective_iam_policies(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py deleted file mode 100644 index f64e953a..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for BatchGetEffectiveIamPolicies -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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 asset_v1 - - -def sample_batch_get_effective_iam_policies(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.BatchGetEffectiveIamPoliciesRequest( - scope="scope_value", - names=['names_value1', 'names_value2'], - ) - - # Make the request - response = client.batch_get_effective_iam_policies(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py deleted file mode 100644 index f5aaf9a0..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_CreateFeed_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 asset_v1 - - -async def sample_create_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = await client.create_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_CreateFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py deleted file mode 100644 index 4ef06854..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_feed_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_CreateFeed_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 asset_v1 - - -def sample_create_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = client.create_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_CreateFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py deleted file mode 100644 index b495af66..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_CreateSavedQuery_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 asset_v1 - - -async def sample_create_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.CreateSavedQueryRequest( - parent="parent_value", - saved_query_id="saved_query_id_value", - ) - - # Make the request - response = await client.create_saved_query(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_CreateSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py deleted file mode 100644 index bdebace2..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_create_saved_query_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_CreateSavedQuery_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 asset_v1 - - -def sample_create_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.CreateSavedQueryRequest( - parent="parent_value", - saved_query_id="saved_query_id_value", - ) - - # Make the request - response = client.create_saved_query(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_CreateSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py deleted file mode 100644 index cd3fab7c..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_DeleteFeed_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 asset_v1 - - -async def sample_delete_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - await client.delete_feed(request=request) - - -# [END cloudasset_v1_generated_AssetService_DeleteFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py deleted file mode 100644 index b6edad9d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_feed_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_DeleteFeed_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 asset_v1 - - -def sample_delete_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - client.delete_feed(request=request) - - -# [END cloudasset_v1_generated_AssetService_DeleteFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py deleted file mode 100644 index 40cdf7f6..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_DeleteSavedQuery_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 asset_v1 - - -async def sample_delete_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.DeleteSavedQueryRequest( - name="name_value", - ) - - # Make the request - await client.delete_saved_query(request=request) - - -# [END cloudasset_v1_generated_AssetService_DeleteSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py deleted file mode 100644 index 29d2ed16..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_delete_saved_query_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_DeleteSavedQuery_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 asset_v1 - - -def sample_delete_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.DeleteSavedQueryRequest( - name="name_value", - ) - - # Make the request - client.delete_saved_query(request=request) - - -# [END cloudasset_v1_generated_AssetService_DeleteSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py deleted file mode 100644 index bc593077..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ExportAssets_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 asset_v1 - - -async def sample_export_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - output_config = asset_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.ExportAssetsRequest( - parent="parent_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_assets(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_ExportAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py deleted file mode 100644 index 0e402bbf..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_export_assets_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ExportAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ExportAssets_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 asset_v1 - - -def sample_export_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - output_config = asset_v1.OutputConfig() - output_config.gcs_destination.uri = "uri_value" - - request = asset_v1.ExportAssetsRequest( - parent="parent_value", - output_config=output_config, - ) - - # Make the request - operation = client.export_assets(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_ExportAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py deleted file mode 100644 index 75bdd2fd..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_GetFeed_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 asset_v1 - - -async def sample_get_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = await client.get_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_GetFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py deleted file mode 100644 index 01cd552c..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_feed_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_GetFeed_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 asset_v1 - - -def sample_get_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = client.get_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_GetFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py deleted file mode 100644 index 7f218510..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_GetSavedQuery_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 asset_v1 - - -async def sample_get_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.GetSavedQueryRequest( - name="name_value", - ) - - # Make the request - response = await client.get_saved_query(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_GetSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py deleted file mode 100644 index 947c761d..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_get_saved_query_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_GetSavedQuery_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 asset_v1 - - -def sample_get_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.GetSavedQueryRequest( - name="name_value", - ) - - # Make the request - response = client.get_saved_query(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_GetSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py deleted file mode 100644 index 91bc6e83..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ListAssets_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 asset_v1 - - -async def sample_list_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_ListAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py deleted file mode 100644 index cbd05991..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_assets_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ListAssets_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 asset_v1 - - -def sample_list_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_ListAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py deleted file mode 100644 index 52059178..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListFeeds -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ListFeeds_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 asset_v1 - - -async def sample_list_feeds(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_feeds(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_ListFeeds_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py deleted file mode 100644 index 2c516167..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_feeds_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListFeeds -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ListFeeds_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 asset_v1 - - -def sample_list_feeds(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_feeds(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_ListFeeds_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py deleted file mode 100644 index c4be56a4..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSavedQueries -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ListSavedQueries_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 asset_v1 - - -async def sample_list_saved_queries(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.ListSavedQueriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_saved_queries(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_ListSavedQueries_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py deleted file mode 100644 index 9825502a..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_list_saved_queries_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListSavedQueries -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_ListSavedQueries_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 asset_v1 - - -def sample_list_saved_queries(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.ListSavedQueriesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_saved_queries(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_ListSavedQueries_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py deleted file mode 100644 index bd68125c..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for QueryAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_QueryAssets_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 asset_v1 - - -async def sample_query_assets(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.QueryAssetsRequest( - statement="statement_value", - parent="parent_value", - ) - - # Make the request - response = await client.query_assets(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_QueryAssets_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py deleted file mode 100644 index e64414fd..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_query_assets_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for QueryAssets -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_QueryAssets_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 asset_v1 - - -def sample_query_assets(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.QueryAssetsRequest( - statement="statement_value", - parent="parent_value", - ) - - # Make the request - response = client.query_assets(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_QueryAssets_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py deleted file mode 100644 index f99c4503..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllIamPolicies -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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 asset_v1 - - -async def sample_search_all_iam_policies(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_SearchAllIamPolicies_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py deleted file mode 100644 index 2095ee02..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllIamPolicies -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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 asset_v1 - - -def sample_search_all_iam_policies(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_SearchAllIamPolicies_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py deleted file mode 100644 index 6e228419..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllResources -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_SearchAllResources_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 asset_v1 - - -async def sample_search_all_resources(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_SearchAllResources_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py deleted file mode 100644 index 4a82b7eb..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_search_all_resources_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllResources -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_SearchAllResources_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 asset_v1 - - -def sample_search_all_resources(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1_generated_AssetService_SearchAllResources_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py deleted file mode 100644 index 80d4dca4..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_UpdateFeed_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 asset_v1 - - -async def sample_update_feed(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = await client.update_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_UpdateFeed_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py deleted file mode 100644 index da3483f2..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_feed_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFeed -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_UpdateFeed_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 asset_v1 - - -def sample_update_feed(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1.Feed() - feed.name = "name_value" - - request = asset_v1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = client.update_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_UpdateFeed_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py deleted file mode 100644 index 56aaab9f..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_UpdateSavedQuery_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 asset_v1 - - -async def sample_update_saved_query(): - # Create a client - client = asset_v1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1.UpdateSavedQueryRequest( - ) - - # Make the request - response = await client.update_saved_query(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_UpdateSavedQuery_async] diff --git a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py b/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py deleted file mode 100644 index ef6a45d6..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/cloudasset_v1_generated_asset_service_update_saved_query_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateSavedQuery -# 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-asset - - -# [START cloudasset_v1_generated_AssetService_UpdateSavedQuery_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 asset_v1 - - -def sample_update_saved_query(): - # Create a client - client = asset_v1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1.UpdateSavedQueryRequest( - ) - - # Make the request - response = client.update_saved_query(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1_generated_AssetService_UpdateSavedQuery_sync] diff --git a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json b/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json deleted file mode 100644 index 5a90dfa8..00000000 --- a/owl-bot-staging/v1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1.json +++ /dev/null @@ -1,3746 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.asset.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-asset", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_iam_policy_longrunning", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeIamPolicyLongrunning" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest" - }, - { - "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": "analyze_iam_policy_longrunning" - }, - "description": "Sample for AnalyzeIamPolicyLongrunning", - "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_async", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_iam_policy_longrunning", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeIamPolicyLongrunning" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest" - }, - { - "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": "analyze_iam_policy_longrunning" - }, - "description": "Sample for AnalyzeIamPolicyLongrunning", - "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicyLongrunning_sync", - "segments": [ - { - "end": 62, - "start": 27, - "type": "FULL" - }, - { - "end": 62, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 52, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 59, - "start": 53, - "type": "REQUEST_EXECUTION" - }, - { - "end": 63, - "start": 60, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_longrunning_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_iam_policy", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicy", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.AnalyzeIamPolicyResponse", - "shortName": "analyze_iam_policy" - }, - "description": "Sample for AnalyzeIamPolicy", - "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_iam_policy", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeIamPolicy", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeIamPolicy" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeIamPolicyRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.AnalyzeIamPolicyResponse", - "shortName": "analyze_iam_policy" - }, - "description": "Sample for AnalyzeIamPolicy", - "file": "cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeIamPolicy_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_iam_policy_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_move", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeMove", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeMove" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeMoveRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.AnalyzeMoveResponse", - "shortName": "analyze_move" - }, - "description": "Sample for AnalyzeMove", - "file": "cloudasset_v1_generated_asset_service_analyze_move_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeMove_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": "cloudasset_v1_generated_asset_service_analyze_move_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_move", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeMove", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeMove" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeMoveRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.AnalyzeMoveResponse", - "shortName": "analyze_move" - }, - "description": "Sample for AnalyzeMove", - "file": "cloudasset_v1_generated_asset_service_analyze_move_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeMove_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": "cloudasset_v1_generated_asset_service_analyze_move_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_org_policies", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeOrgPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "constraint", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesAsyncPager", - "shortName": "analyze_org_policies" - }, - "description": "Sample for AnalyzeOrgPolicies", - "file": "cloudasset_v1_generated_asset_service_analyze_org_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_org_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_org_policies", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicies", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeOrgPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeOrgPoliciesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "constraint", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPoliciesPager", - "shortName": "analyze_org_policies" - }, - "description": "Sample for AnalyzeOrgPolicies", - "file": "cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicies_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_org_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_org_policy_governed_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeOrgPolicyGovernedAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "constraint", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager", - "shortName": "analyze_org_policy_governed_assets" - }, - "description": "Sample for AnalyzeOrgPolicyGovernedAssets", - "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_org_policy_governed_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeOrgPolicyGovernedAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedAssetsRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "constraint", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedAssetsPager", - "shortName": "analyze_org_policy_governed_assets" - }, - "description": "Sample for AnalyzeOrgPolicyGovernedAssets", - "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedAssets_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.analyze_org_policy_governed_containers", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeOrgPolicyGovernedContainers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "constraint", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager", - "shortName": "analyze_org_policy_governed_containers" - }, - "description": "Sample for AnalyzeOrgPolicyGovernedContainers", - "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.analyze_org_policy_governed_containers", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.AnalyzeOrgPolicyGovernedContainers", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "AnalyzeOrgPolicyGovernedContainers" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.AnalyzeOrgPolicyGovernedContainersRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "constraint", - "type": "str" - }, - { - "name": "filter", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.AnalyzeOrgPolicyGovernedContainersPager", - "shortName": "analyze_org_policy_governed_containers" - }, - "description": "Sample for AnalyzeOrgPolicyGovernedContainers", - "file": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_AnalyzeOrgPolicyGovernedContainers_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_analyze_org_policy_governed_containers_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.batch_get_assets_history", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.BatchGetAssetsHistory", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "BatchGetAssetsHistory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse", - "shortName": "batch_get_assets_history" - }, - "description": "Sample for BatchGetAssetsHistory", - "file": "cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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": "cloudasset_v1_generated_asset_service_batch_get_assets_history_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.batch_get_assets_history", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.BatchGetAssetsHistory", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "BatchGetAssetsHistory" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.BatchGetAssetsHistoryRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.BatchGetAssetsHistoryResponse", - "shortName": "batch_get_assets_history" - }, - "description": "Sample for BatchGetAssetsHistory", - "file": "cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_BatchGetAssetsHistory_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": "cloudasset_v1_generated_asset_service_batch_get_assets_history_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.batch_get_effective_iam_policies", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "BatchGetEffectiveIamPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse", - "shortName": "batch_get_effective_iam_policies" - }, - "description": "Sample for BatchGetEffectiveIamPolicies", - "file": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.batch_get_effective_iam_policies", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.BatchGetEffectiveIamPolicies", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "BatchGetEffectiveIamPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.BatchGetEffectiveIamPoliciesResponse", - "shortName": "batch_get_effective_iam_policies" - }, - "description": "Sample for BatchGetEffectiveIamPolicies", - "file": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_BatchGetEffectiveIamPolicies_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": "cloudasset_v1_generated_asset_service_batch_get_effective_iam_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.create_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.CreateFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "CreateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.CreateFeedRequest" - }, - { - "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.asset_v1.types.Feed", - "shortName": "create_feed" - }, - "description": "Sample for CreateFeed", - "file": "cloudasset_v1_generated_asset_service_create_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_CreateFeed_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_create_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.create_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.CreateFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "CreateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.CreateFeedRequest" - }, - { - "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.asset_v1.types.Feed", - "shortName": "create_feed" - }, - "description": "Sample for CreateFeed", - "file": "cloudasset_v1_generated_asset_service_create_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_CreateFeed_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_create_feed_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.create_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.CreateSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "CreateSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.CreateSavedQueryRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "saved_query", - "type": "google.cloud.asset_v1.types.SavedQuery" - }, - { - "name": "saved_query_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.asset_v1.types.SavedQuery", - "shortName": "create_saved_query" - }, - "description": "Sample for CreateSavedQuery", - "file": "cloudasset_v1_generated_asset_service_create_saved_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_CreateSavedQuery_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": "cloudasset_v1_generated_asset_service_create_saved_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.create_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.CreateSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "CreateSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.CreateSavedQueryRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "saved_query", - "type": "google.cloud.asset_v1.types.SavedQuery" - }, - { - "name": "saved_query_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.asset_v1.types.SavedQuery", - "shortName": "create_saved_query" - }, - "description": "Sample for CreateSavedQuery", - "file": "cloudasset_v1_generated_asset_service_create_saved_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_CreateSavedQuery_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": "cloudasset_v1_generated_asset_service_create_saved_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.delete_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.DeleteFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "DeleteFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.DeleteFeedRequest" - }, - { - "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_feed" - }, - "description": "Sample for DeleteFeed", - "file": "cloudasset_v1_generated_asset_service_delete_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_DeleteFeed_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": "cloudasset_v1_generated_asset_service_delete_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.delete_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.DeleteFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "DeleteFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.DeleteFeedRequest" - }, - { - "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_feed" - }, - "description": "Sample for DeleteFeed", - "file": "cloudasset_v1_generated_asset_service_delete_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_DeleteFeed_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": "cloudasset_v1_generated_asset_service_delete_feed_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.delete_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.DeleteSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "DeleteSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.DeleteSavedQueryRequest" - }, - { - "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_saved_query" - }, - "description": "Sample for DeleteSavedQuery", - "file": "cloudasset_v1_generated_asset_service_delete_saved_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_DeleteSavedQuery_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": "cloudasset_v1_generated_asset_service_delete_saved_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.delete_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.DeleteSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "DeleteSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.DeleteSavedQueryRequest" - }, - { - "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_saved_query" - }, - "description": "Sample for DeleteSavedQuery", - "file": "cloudasset_v1_generated_asset_service_delete_saved_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_DeleteSavedQuery_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": "cloudasset_v1_generated_asset_service_delete_saved_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.export_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ExportAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ExportAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ExportAssetsRequest" - }, - { - "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": "export_assets" - }, - "description": "Sample for ExportAssets", - "file": "cloudasset_v1_generated_asset_service_export_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ExportAssets_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_export_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.export_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ExportAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ExportAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ExportAssetsRequest" - }, - { - "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": "export_assets" - }, - "description": "Sample for ExportAssets", - "file": "cloudasset_v1_generated_asset_service_export_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ExportAssets_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_export_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.get_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.GetFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "GetFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.GetFeedRequest" - }, - { - "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.asset_v1.types.Feed", - "shortName": "get_feed" - }, - "description": "Sample for GetFeed", - "file": "cloudasset_v1_generated_asset_service_get_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_GetFeed_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": "cloudasset_v1_generated_asset_service_get_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.get_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.GetFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "GetFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.GetFeedRequest" - }, - { - "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.asset_v1.types.Feed", - "shortName": "get_feed" - }, - "description": "Sample for GetFeed", - "file": "cloudasset_v1_generated_asset_service_get_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_GetFeed_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": "cloudasset_v1_generated_asset_service_get_feed_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.get_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.GetSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "GetSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.GetSavedQueryRequest" - }, - { - "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.asset_v1.types.SavedQuery", - "shortName": "get_saved_query" - }, - "description": "Sample for GetSavedQuery", - "file": "cloudasset_v1_generated_asset_service_get_saved_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_GetSavedQuery_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": "cloudasset_v1_generated_asset_service_get_saved_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.get_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.GetSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "GetSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.GetSavedQueryRequest" - }, - { - "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.asset_v1.types.SavedQuery", - "shortName": "get_saved_query" - }, - "description": "Sample for GetSavedQuery", - "file": "cloudasset_v1_generated_asset_service_get_saved_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_GetSavedQuery_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": "cloudasset_v1_generated_asset_service_get_saved_query_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ListAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ListAssetsRequest" - }, - { - "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.asset_v1.services.asset_service.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "cloudasset_v1_generated_asset_service_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ListAssets_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": "cloudasset_v1_generated_asset_service_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.list_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ListAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ListAssetsRequest" - }, - { - "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.asset_v1.services.asset_service.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "cloudasset_v1_generated_asset_service_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ListAssets_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": "cloudasset_v1_generated_asset_service_list_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.list_feeds", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ListFeeds", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListFeeds" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ListFeedsRequest" - }, - { - "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.asset_v1.types.ListFeedsResponse", - "shortName": "list_feeds" - }, - "description": "Sample for ListFeeds", - "file": "cloudasset_v1_generated_asset_service_list_feeds_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ListFeeds_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": "cloudasset_v1_generated_asset_service_list_feeds_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.list_feeds", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ListFeeds", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListFeeds" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ListFeedsRequest" - }, - { - "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.asset_v1.types.ListFeedsResponse", - "shortName": "list_feeds" - }, - "description": "Sample for ListFeeds", - "file": "cloudasset_v1_generated_asset_service_list_feeds_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ListFeeds_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": "cloudasset_v1_generated_asset_service_list_feeds_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.list_saved_queries", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ListSavedQueries", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListSavedQueries" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ListSavedQueriesRequest" - }, - { - "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.asset_v1.services.asset_service.pagers.ListSavedQueriesAsyncPager", - "shortName": "list_saved_queries" - }, - "description": "Sample for ListSavedQueries", - "file": "cloudasset_v1_generated_asset_service_list_saved_queries_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ListSavedQueries_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": "cloudasset_v1_generated_asset_service_list_saved_queries_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.list_saved_queries", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.ListSavedQueries", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListSavedQueries" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.ListSavedQueriesRequest" - }, - { - "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.asset_v1.services.asset_service.pagers.ListSavedQueriesPager", - "shortName": "list_saved_queries" - }, - "description": "Sample for ListSavedQueries", - "file": "cloudasset_v1_generated_asset_service_list_saved_queries_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_ListSavedQueries_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": "cloudasset_v1_generated_asset_service_list_saved_queries_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.query_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.QueryAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "QueryAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.QueryAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.QueryAssetsResponse", - "shortName": "query_assets" - }, - "description": "Sample for QueryAssets", - "file": "cloudasset_v1_generated_asset_service_query_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_QueryAssets_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": "cloudasset_v1_generated_asset_service_query_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.query_assets", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.QueryAssets", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "QueryAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.QueryAssetsRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.QueryAssetsResponse", - "shortName": "query_assets" - }, - "description": "Sample for QueryAssets", - "file": "cloudasset_v1_generated_asset_service_query_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_QueryAssets_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": "cloudasset_v1_generated_asset_service_query_assets_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.search_all_iam_policies", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.SearchAllIamPolicies", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllIamPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.SearchAllIamPoliciesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager", - "shortName": "search_all_iam_policies" - }, - "description": "Sample for SearchAllIamPolicies", - "file": "cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1_generated_asset_service_search_all_iam_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.search_all_iam_policies", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.SearchAllIamPolicies", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllIamPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.SearchAllIamPoliciesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllIamPoliciesPager", - "shortName": "search_all_iam_policies" - }, - "description": "Sample for SearchAllIamPolicies", - "file": "cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1_generated_asset_service_search_all_iam_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.search_all_resources", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.SearchAllResources", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.SearchAllResourcesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "asset_types", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllResourcesAsyncPager", - "shortName": "search_all_resources" - }, - "description": "Sample for SearchAllResources", - "file": "cloudasset_v1_generated_asset_service_search_all_resources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_SearchAllResources_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": "cloudasset_v1_generated_asset_service_search_all_resources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.search_all_resources", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.SearchAllResources", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.SearchAllResourcesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "asset_types", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.services.asset_service.pagers.SearchAllResourcesPager", - "shortName": "search_all_resources" - }, - "description": "Sample for SearchAllResources", - "file": "cloudasset_v1_generated_asset_service_search_all_resources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_SearchAllResources_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": "cloudasset_v1_generated_asset_service_search_all_resources_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.update_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.UpdateFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "UpdateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.UpdateFeedRequest" - }, - { - "name": "feed", - "type": "google.cloud.asset_v1.types.Feed" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.Feed", - "shortName": "update_feed" - }, - "description": "Sample for UpdateFeed", - "file": "cloudasset_v1_generated_asset_service_update_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_UpdateFeed_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_update_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.update_feed", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.UpdateFeed", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "UpdateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.UpdateFeedRequest" - }, - { - "name": "feed", - "type": "google.cloud.asset_v1.types.Feed" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1.types.Feed", - "shortName": "update_feed" - }, - "description": "Sample for UpdateFeed", - "file": "cloudasset_v1_generated_asset_service_update_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_UpdateFeed_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1_generated_asset_service_update_feed_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceAsyncClient.update_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.UpdateSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "UpdateSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.UpdateSavedQueryRequest" - }, - { - "name": "saved_query", - "type": "google.cloud.asset_v1.types.SavedQuery" - }, - { - "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.asset_v1.types.SavedQuery", - "shortName": "update_saved_query" - }, - "description": "Sample for UpdateSavedQuery", - "file": "cloudasset_v1_generated_asset_service_update_saved_query_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_UpdateSavedQuery_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": "cloudasset_v1_generated_asset_service_update_saved_query_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1.AssetServiceClient.update_saved_query", - "method": { - "fullName": "google.cloud.asset.v1.AssetService.UpdateSavedQuery", - "service": { - "fullName": "google.cloud.asset.v1.AssetService", - "shortName": "AssetService" - }, - "shortName": "UpdateSavedQuery" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1.types.UpdateSavedQueryRequest" - }, - { - "name": "saved_query", - "type": "google.cloud.asset_v1.types.SavedQuery" - }, - { - "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.asset_v1.types.SavedQuery", - "shortName": "update_saved_query" - }, - "description": "Sample for UpdateSavedQuery", - "file": "cloudasset_v1_generated_asset_service_update_saved_query_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1_generated_AssetService_UpdateSavedQuery_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": "cloudasset_v1_generated_asset_service_update_saved_query_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py b/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py deleted file mode 100644 index 979373d9..00000000 --- a/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 assetCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_iam_policy': ('analysis_query', 'saved_analysis_query', 'execution_timeout', ), - 'analyze_iam_policy_longrunning': ('analysis_query', 'output_config', 'saved_analysis_query', ), - 'analyze_move': ('resource', 'destination_parent', 'view', ), - 'analyze_org_policies': ('scope', 'constraint', 'filter', 'page_size', 'page_token', ), - 'analyze_org_policy_governed_assets': ('scope', 'constraint', 'filter', 'page_size', 'page_token', ), - 'analyze_org_policy_governed_containers': ('scope', 'constraint', 'filter', 'page_size', 'page_token', ), - 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', 'relationship_types', ), - 'batch_get_effective_iam_policies': ('scope', 'names', ), - 'create_feed': ('parent', 'feed_id', 'feed', ), - 'create_saved_query': ('parent', 'saved_query', 'saved_query_id', ), - 'delete_feed': ('name', ), - 'delete_saved_query': ('name', ), - 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', 'relationship_types', ), - 'get_feed': ('name', ), - 'get_saved_query': ('name', ), - 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', 'relationship_types', ), - 'list_feeds': ('parent', ), - 'list_saved_queries': ('parent', 'filter', 'page_size', 'page_token', ), - 'query_assets': ('parent', 'statement', 'job_reference', 'page_size', 'page_token', 'timeout', 'read_time_window', 'read_time', 'output_config', ), - 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', 'asset_types', 'order_by', ), - 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', 'read_mask', ), - 'update_feed': ('feed', 'update_mask', ), - 'update_saved_query': ('saved_query', 'update_mask', ), - } - - 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=assetCallTransformer(), -): - """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 asset 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 166120b0..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-asset' - - -description = "Google Cloud Asset API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/asset/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-asset" - -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 ad3f0fa5..00000000 --- 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 ad3f0fa5..00000000 --- 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 ad3f0fa5..00000000 --- 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 2beecf99..00000000 --- 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 ad3f0fa5..00000000 --- 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 ad3f0fa5..00000000 --- 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 1b4db446..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# 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 1b4db446..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# 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 1b4db446..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py deleted file mode 100644 index 497b0ed2..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py +++ /dev/null @@ -1,13601 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.asset_v1.services.asset_service import AssetServiceAsyncClient -from google.cloud.asset_v1.services.asset_service import AssetServiceClient -from google.cloud.asset_v1.services.asset_service import pagers -from google.cloud.asset_v1.services.asset_service import transports -from google.cloud.asset_v1.types import asset_service -from google.cloud.asset_v1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.rpc import status_pb2 # type: ignore -from google.type import expr_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 AssetServiceClient._get_default_mtls_endpoint(None) is None - assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceRestTransport, - ] - assert transport in available_transports - - transport = AssetServiceClient.get_transport_class("grpc") - assert transport == transports.AssetServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_asset_service_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", [ - AssetServiceClient, AssetServiceAsyncClient -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), -]) -def test_asset_service_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_asset_service_client_client_options_from_dict(): - with mock.patch('google.cloud.asset_v1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ExportAssetsRequest, - dict, -]) -def test_export_assets(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.export_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ExportAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_assets_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 = AssetServiceClient( - 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.export_assets), - '__call__') as call: - client.export_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ExportAssetsRequest() - -@pytest.mark.asyncio -async def test_export_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.ExportAssetsRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.export_assets), - '__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.export_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ExportAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_assets_async_from_dict(): - await test_export_assets_async(request_type=dict) - - -def test_export_assets_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ExportAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_assets), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_assets(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_export_assets_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ExportAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_assets(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'] - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListAssetsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_assets_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 = AssetServiceClient( - 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_assets), - '__call__') as call: - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListAssetsRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = asset_service.ListAssetsResponse() - client.list_assets(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_assets_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) - await client.list_assets(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_assets_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListAssetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_assets( - 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_assets_flattened_error(): - client = AssetServiceClient( - 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_assets( - asset_service.ListAssetsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_assets_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListAssetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_assets( - 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_assets_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_assets( - asset_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.Asset) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, assets.Asset) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_assets(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - asset_service.BatchGetAssetsHistoryRequest, - dict, -]) -def test_batch_get_assets_history(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.batch_get_assets_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.BatchGetAssetsHistoryResponse( - ) - response = client.batch_get_assets_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.BatchGetAssetsHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) - - -def test_batch_get_assets_history_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 = AssetServiceClient( - 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.batch_get_assets_history), - '__call__') as call: - client.batch_get_assets_history() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.BatchGetAssetsHistoryRequest() - -@pytest.mark.asyncio -async def test_batch_get_assets_history_async(transport: str = 'grpc_asyncio', request_type=asset_service.BatchGetAssetsHistoryRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.batch_get_assets_history), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetAssetsHistoryResponse( - )) - response = await client.batch_get_assets_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.BatchGetAssetsHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) - - -@pytest.mark.asyncio -async def test_batch_get_assets_history_async_from_dict(): - await test_batch_get_assets_history_async(request_type=dict) - - -def test_batch_get_assets_history_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.BatchGetAssetsHistoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_assets_history), - '__call__') as call: - call.return_value = asset_service.BatchGetAssetsHistoryResponse() - client.batch_get_assets_history(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_batch_get_assets_history_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.BatchGetAssetsHistoryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_assets_history), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetAssetsHistoryResponse()) - await client.batch_get_assets_history(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'] - - -@pytest.mark.parametrize("request_type", [ - asset_service.CreateFeedRequest, - dict, -]) -def test_create_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - ) - response = client.create_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -def test_create_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.create_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() - -@pytest.mark.asyncio -async def test_create_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.CreateFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - )) - response = await client.create_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -@pytest.mark.asyncio -async def test_create_feed_async_from_dict(): - await test_create_feed_async(request_type=dict) - - -def test_create_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.CreateFeedRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - call.return_value = asset_service.Feed() - client.create_feed(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_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.CreateFeedRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.create_feed(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_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_feed( - 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_create_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.CreateFeedRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_create_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_feed( - 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_create_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.CreateFeedRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.GetFeedRequest, - dict, -]) -def test_get_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - ) - response = client.get_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -def test_get_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.get_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() - -@pytest.mark.asyncio -async def test_get_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.GetFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - )) - response = await client.get_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -@pytest.mark.asyncio -async def test_get_feed_async_from_dict(): - await test_get_feed_async(request_type=dict) - - -def test_get_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.GetFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - call.return_value = asset_service.Feed() - client.get_feed(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_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.GetFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.get_feed(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_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_feed( - 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_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.GetFeedRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_feed( - 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_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.GetFeedRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListFeedsRequest, - dict, -]) -def test_list_feeds(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListFeedsResponse( - ) - response = client.list_feeds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) - - -def test_list_feeds_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 = AssetServiceClient( - 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_feeds), - '__call__') as call: - client.list_feeds() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() - -@pytest.mark.asyncio -async def test_list_feeds_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListFeedsRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse( - )) - response = await client.list_feeds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) - - -@pytest.mark.asyncio -async def test_list_feeds_async_from_dict(): - await test_list_feeds_async(request_type=dict) - - -def test_list_feeds_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListFeedsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - call.return_value = asset_service.ListFeedsResponse() - client.list_feeds(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_feeds_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListFeedsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) - await client.list_feeds(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_feeds_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListFeedsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_feeds( - 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_feeds_flattened_error(): - client = AssetServiceClient( - 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_feeds( - asset_service.ListFeedsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_feeds_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListFeedsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_feeds( - 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_feeds_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feeds( - asset_service.ListFeedsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.UpdateFeedRequest, - dict, -]) -def test_update_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - ) - response = client.update_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -def test_update_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.update_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() - -@pytest.mark.asyncio -async def test_update_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.UpdateFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - )) - response = await client.update_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -@pytest.mark.asyncio -async def test_update_feed_async_from_dict(): - await test_update_feed_async(request_type=dict) - - -def test_update_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.UpdateFeedRequest() - - request.feed.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - call.return_value = asset_service.Feed() - client.update_feed(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', - 'feed.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.UpdateFeedRequest() - - request.feed.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.update_feed(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', - 'feed.name=name_value', - ) in kw['metadata'] - - -def test_update_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_feed( - feed=asset_service.Feed(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].feed - mock_val = asset_service.Feed(name='name_value') - assert arg == mock_val - - -def test_update_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.UpdateFeedRequest(), - feed=asset_service.Feed(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_feed( - feed=asset_service.Feed(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].feed - mock_val = asset_service.Feed(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.UpdateFeedRequest(), - feed=asset_service.Feed(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.DeleteFeedRequest, - dict, -]) -def test_delete_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.delete_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() - -@pytest.mark.asyncio -async def test_delete_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.DeleteFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_feed_async_from_dict(): - await test_delete_feed_async(request_type=dict) - - -def test_delete_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.DeleteFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__call__') as call: - call.return_value = None - client.delete_feed(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_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.DeleteFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_feed(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_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__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_feed( - 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_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.DeleteFeedRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__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_feed( - 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_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.DeleteFeedRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.SearchAllResourcesRequest, - dict, -]) -def test_search_all_resources(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllResourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.search_all_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_resources_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 = AssetServiceClient( - 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.search_all_resources), - '__call__') as call: - client.search_all_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() - -@pytest.mark.asyncio -async def test_search_all_resources_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllResourcesRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_all_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_all_resources_async_from_dict(): - await test_search_all_resources_async(request_type=dict) - - -def test_search_all_resources_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllResourcesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - call.return_value = asset_service.SearchAllResourcesResponse() - client.search_all_resources(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_all_resources_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllResourcesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) - await client.search_all_resources(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', - 'scope=scope_value', - ) in kw['metadata'] - - -def test_search_all_resources_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllResourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_all_resources( - scope='scope_value', - query='query_value', - asset_types=['asset_types_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - arg = args[0].asset_types - mock_val = ['asset_types_value'] - assert arg == mock_val - - -def test_search_all_resources_flattened_error(): - client = AssetServiceClient( - 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.search_all_resources( - asset_service.SearchAllResourcesRequest(), - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - -@pytest.mark.asyncio -async def test_search_all_resources_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllResourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_all_resources( - scope='scope_value', - query='query_value', - asset_types=['asset_types_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - arg = args[0].asset_types - mock_val = ['asset_types_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_all_resources_flattened_error_async(): - client = AssetServiceAsyncClient( - 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.search_all_resources( - asset_service.SearchAllResourcesRequest(), - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - - -def test_search_all_resources_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('scope', ''), - )), - ) - pager = client.search_all_resources(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.ResourceSearchResult) - for i in results) -def test_search_all_resources_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search_all_resources(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_search_all_resources_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_all_resources(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, assets.ResourceSearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_all_resources_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search_all_resources(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - asset_service.SearchAllIamPoliciesRequest, - dict, -]) -def test_search_all_iam_policies(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllIamPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.search_all_iam_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_iam_policies_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 = AssetServiceClient( - 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.search_all_iam_policies), - '__call__') as call: - client.search_all_iam_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() - -@pytest.mark.asyncio -async def test_search_all_iam_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllIamPoliciesRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_all_iam_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_all_iam_policies_async_from_dict(): - await test_search_all_iam_policies_async(request_type=dict) - - -def test_search_all_iam_policies_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllIamPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - call.return_value = asset_service.SearchAllIamPoliciesResponse() - client.search_all_iam_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_all_iam_policies_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllIamPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) - await client.search_all_iam_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -def test_search_all_iam_policies_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllIamPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_all_iam_policies( - scope='scope_value', - query='query_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - - -def test_search_all_iam_policies_flattened_error(): - client = AssetServiceClient( - 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.search_all_iam_policies( - asset_service.SearchAllIamPoliciesRequest(), - scope='scope_value', - query='query_value', - ) - -@pytest.mark.asyncio -async def test_search_all_iam_policies_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllIamPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_all_iam_policies( - scope='scope_value', - query='query_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_all_iam_policies_flattened_error_async(): - client = AssetServiceAsyncClient( - 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.search_all_iam_policies( - asset_service.SearchAllIamPoliciesRequest(), - scope='scope_value', - query='query_value', - ) - - -def test_search_all_iam_policies_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_iam_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('scope', ''), - )), - ) - pager = client.search_all_iam_policies(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.IamPolicySearchResult) - for i in results) -def test_search_all_iam_policies_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_iam_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search_all_iam_policies(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_search_all_iam_policies_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_all_iam_policies(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, assets.IamPolicySearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_all_iam_policies_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search_all_iam_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeIamPolicyRequest, - dict, -]) -def test_analyze_iam_policy(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeIamPolicyResponse( - fully_explored=True, - ) - response = client.analyze_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] == asset_service.AnalyzeIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) - assert response.fully_explored is True - - -def test_analyze_iam_policy_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 = AssetServiceClient( - 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.analyze_iam_policy), - '__call__') as call: - client.analyze_iam_policy() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeIamPolicyRequest() - -@pytest.mark.asyncio -async def test_analyze_iam_policy_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeIamPolicyRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_iam_policy), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeIamPolicyResponse( - fully_explored=True, - )) - response = await client.analyze_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] == asset_service.AnalyzeIamPolicyRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) - assert response.fully_explored is True - - -@pytest.mark.asyncio -async def test_analyze_iam_policy_async_from_dict(): - await test_analyze_iam_policy_async(request_type=dict) - - -def test_analyze_iam_policy_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeIamPolicyRequest() - - request.analysis_query.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_iam_policy), - '__call__') as call: - call.return_value = asset_service.AnalyzeIamPolicyResponse() - client.analyze_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', - 'analysis_query.scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_analyze_iam_policy_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeIamPolicyRequest() - - request.analysis_query.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_iam_policy), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeIamPolicyResponse()) - await client.analyze_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', - 'analysis_query.scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeIamPolicyLongrunningRequest, - dict, -]) -def test_analyze_iam_policy_longrunning(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_iam_policy_longrunning), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.analyze_iam_policy_longrunning(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeIamPolicyLongrunningRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_analyze_iam_policy_longrunning_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 = AssetServiceClient( - 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.analyze_iam_policy_longrunning), - '__call__') as call: - client.analyze_iam_policy_longrunning() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeIamPolicyLongrunningRequest() - -@pytest.mark.asyncio -async def test_analyze_iam_policy_longrunning_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_iam_policy_longrunning), - '__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.analyze_iam_policy_longrunning(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeIamPolicyLongrunningRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_analyze_iam_policy_longrunning_async_from_dict(): - await test_analyze_iam_policy_longrunning_async(request_type=dict) - - -def test_analyze_iam_policy_longrunning_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeIamPolicyLongrunningRequest() - - request.analysis_query.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_iam_policy_longrunning), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.analyze_iam_policy_longrunning(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', - 'analysis_query.scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_analyze_iam_policy_longrunning_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeIamPolicyLongrunningRequest() - - request.analysis_query.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_iam_policy_longrunning), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.analyze_iam_policy_longrunning(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', - 'analysis_query.scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeMoveRequest, - dict, -]) -def test_analyze_move(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_move), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeMoveResponse( - ) - response = client.analyze_move(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeMoveRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeMoveResponse) - - -def test_analyze_move_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 = AssetServiceClient( - 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.analyze_move), - '__call__') as call: - client.analyze_move() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeMoveRequest() - -@pytest.mark.asyncio -async def test_analyze_move_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeMoveRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_move), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeMoveResponse( - )) - response = await client.analyze_move(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeMoveRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeMoveResponse) - - -@pytest.mark.asyncio -async def test_analyze_move_async_from_dict(): - await test_analyze_move_async(request_type=dict) - - -def test_analyze_move_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeMoveRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_move), - '__call__') as call: - call.return_value = asset_service.AnalyzeMoveResponse() - client.analyze_move(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_analyze_move_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeMoveRequest() - - request.resource = 'resource_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_move), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeMoveResponse()) - await client.analyze_move(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'] - - -@pytest.mark.parametrize("request_type", [ - asset_service.QueryAssetsRequest, - dict, -]) -def test_query_assets(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.query_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.QueryAssetsResponse( - job_reference='job_reference_value', - done=True, - ) - response = client.query_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.QueryAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.QueryAssetsResponse) - assert response.job_reference == 'job_reference_value' - assert response.done is True - - -def test_query_assets_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 = AssetServiceClient( - 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.query_assets), - '__call__') as call: - client.query_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.QueryAssetsRequest() - -@pytest.mark.asyncio -async def test_query_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.QueryAssetsRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.query_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.QueryAssetsResponse( - job_reference='job_reference_value', - done=True, - )) - response = await client.query_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.QueryAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.QueryAssetsResponse) - assert response.job_reference == 'job_reference_value' - assert response.done is True - - -@pytest.mark.asyncio -async def test_query_assets_async_from_dict(): - await test_query_assets_async(request_type=dict) - - -def test_query_assets_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.QueryAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.query_assets), - '__call__') as call: - call.return_value = asset_service.QueryAssetsResponse() - client.query_assets(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_query_assets_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.QueryAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.query_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.QueryAssetsResponse()) - await client.query_assets(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'] - - -@pytest.mark.parametrize("request_type", [ - asset_service.CreateSavedQueryRequest, - dict, -]) -def test_create_saved_query(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - ) - response = client.create_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -def test_create_saved_query_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 = AssetServiceClient( - 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_saved_query), - '__call__') as call: - client.create_saved_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateSavedQueryRequest() - -@pytest.mark.asyncio -async def test_create_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.CreateSavedQueryRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - )) - response = await client.create_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -@pytest.mark.asyncio -async def test_create_saved_query_async_from_dict(): - await test_create_saved_query_async(request_type=dict) - - -def test_create_saved_query_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.CreateSavedQueryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_saved_query), - '__call__') as call: - call.return_value = asset_service.SavedQuery() - client.create_saved_query(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_saved_query_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.CreateSavedQueryRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_saved_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) - await client.create_saved_query(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_saved_query_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_saved_query( - parent='parent_value', - saved_query=asset_service.SavedQuery(name='name_value'), - saved_query_id='saved_query_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].saved_query - mock_val = asset_service.SavedQuery(name='name_value') - assert arg == mock_val - arg = args[0].saved_query_id - mock_val = 'saved_query_id_value' - assert arg == mock_val - - -def test_create_saved_query_flattened_error(): - client = AssetServiceClient( - 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_saved_query( - asset_service.CreateSavedQueryRequest(), - parent='parent_value', - saved_query=asset_service.SavedQuery(name='name_value'), - saved_query_id='saved_query_id_value', - ) - -@pytest.mark.asyncio -async def test_create_saved_query_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_saved_query( - parent='parent_value', - saved_query=asset_service.SavedQuery(name='name_value'), - saved_query_id='saved_query_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].saved_query - mock_val = asset_service.SavedQuery(name='name_value') - assert arg == mock_val - arg = args[0].saved_query_id - mock_val = 'saved_query_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_saved_query_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_saved_query( - asset_service.CreateSavedQueryRequest(), - parent='parent_value', - saved_query=asset_service.SavedQuery(name='name_value'), - saved_query_id='saved_query_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.GetSavedQueryRequest, - dict, -]) -def test_get_saved_query(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - ) - response = client.get_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -def test_get_saved_query_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 = AssetServiceClient( - 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_saved_query), - '__call__') as call: - client.get_saved_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetSavedQueryRequest() - -@pytest.mark.asyncio -async def test_get_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.GetSavedQueryRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - )) - response = await client.get_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -@pytest.mark.asyncio -async def test_get_saved_query_async_from_dict(): - await test_get_saved_query_async(request_type=dict) - - -def test_get_saved_query_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.GetSavedQueryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_saved_query), - '__call__') as call: - call.return_value = asset_service.SavedQuery() - client.get_saved_query(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_saved_query_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.GetSavedQueryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_saved_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) - await client.get_saved_query(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_saved_query_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_saved_query( - 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_saved_query_flattened_error(): - client = AssetServiceClient( - 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_saved_query( - asset_service.GetSavedQueryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_saved_query_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_saved_query( - 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_saved_query_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_saved_query( - asset_service.GetSavedQueryRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListSavedQueriesRequest, - dict, -]) -def test_list_saved_queries(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_queries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListSavedQueriesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_saved_queries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListSavedQueriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSavedQueriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_saved_queries_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 = AssetServiceClient( - 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_saved_queries), - '__call__') as call: - client.list_saved_queries() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListSavedQueriesRequest() - -@pytest.mark.asyncio -async def test_list_saved_queries_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListSavedQueriesRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_queries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListSavedQueriesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_saved_queries(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListSavedQueriesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSavedQueriesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_saved_queries_async_from_dict(): - await test_list_saved_queries_async(request_type=dict) - - -def test_list_saved_queries_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListSavedQueriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_saved_queries), - '__call__') as call: - call.return_value = asset_service.ListSavedQueriesResponse() - client.list_saved_queries(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_saved_queries_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListSavedQueriesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_saved_queries), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListSavedQueriesResponse()) - await client.list_saved_queries(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_saved_queries_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_saved_queries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListSavedQueriesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_saved_queries( - 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_saved_queries_flattened_error(): - client = AssetServiceClient( - 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_saved_queries( - asset_service.ListSavedQueriesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_saved_queries_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_saved_queries), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListSavedQueriesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListSavedQueriesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_saved_queries( - 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_saved_queries_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_saved_queries( - asset_service.ListSavedQueriesRequest(), - parent='parent_value', - ) - - -def test_list_saved_queries_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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_saved_queries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - next_page_token='abc', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[], - next_page_token='def', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - ], - next_page_token='ghi', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_saved_queries(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.SavedQuery) - for i in results) -def test_list_saved_queries_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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_saved_queries), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - next_page_token='abc', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[], - next_page_token='def', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - ], - next_page_token='ghi', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - ), - RuntimeError, - ) - pages = list(client.list_saved_queries(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_saved_queries_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_saved_queries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - next_page_token='abc', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[], - next_page_token='def', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - ], - next_page_token='ghi', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_saved_queries(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, asset_service.SavedQuery) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_saved_queries_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_saved_queries), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - next_page_token='abc', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[], - next_page_token='def', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - ], - next_page_token='ghi', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_saved_queries(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - asset_service.UpdateSavedQueryRequest, - dict, -]) -def test_update_saved_query(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - ) - response = client.update_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -def test_update_saved_query_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 = AssetServiceClient( - 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_saved_query), - '__call__') as call: - client.update_saved_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateSavedQueryRequest() - -@pytest.mark.asyncio -async def test_update_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.UpdateSavedQueryRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - )) - response = await client.update_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -@pytest.mark.asyncio -async def test_update_saved_query_async_from_dict(): - await test_update_saved_query_async(request_type=dict) - - -def test_update_saved_query_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.UpdateSavedQueryRequest() - - request.saved_query.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_saved_query), - '__call__') as call: - call.return_value = asset_service.SavedQuery() - client.update_saved_query(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', - 'saved_query.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_saved_query_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.UpdateSavedQueryRequest() - - request.saved_query.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_saved_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) - await client.update_saved_query(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', - 'saved_query.name=name_value', - ) in kw['metadata'] - - -def test_update_saved_query_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_saved_query( - saved_query=asset_service.SavedQuery(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].saved_query - mock_val = asset_service.SavedQuery(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_saved_query_flattened_error(): - client = AssetServiceClient( - 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_saved_query( - asset_service.UpdateSavedQueryRequest(), - saved_query=asset_service.SavedQuery(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_saved_query_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SavedQuery() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SavedQuery()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_saved_query( - saved_query=asset_service.SavedQuery(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].saved_query - mock_val = asset_service.SavedQuery(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_saved_query_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_saved_query( - asset_service.UpdateSavedQueryRequest(), - saved_query=asset_service.SavedQuery(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.DeleteSavedQueryRequest, - dict, -]) -def test_delete_saved_query(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_saved_query_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 = AssetServiceClient( - 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_saved_query), - '__call__') as call: - client.delete_saved_query() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteSavedQueryRequest() - -@pytest.mark.asyncio -async def test_delete_saved_query_async(transport: str = 'grpc_asyncio', request_type=asset_service.DeleteSavedQueryRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_saved_query), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_saved_query(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteSavedQueryRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_saved_query_async_from_dict(): - await test_delete_saved_query_async(request_type=dict) - - -def test_delete_saved_query_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.DeleteSavedQueryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_saved_query), - '__call__') as call: - call.return_value = None - client.delete_saved_query(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_saved_query_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.DeleteSavedQueryRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_saved_query), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_saved_query(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_saved_query_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_saved_query), - '__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_saved_query( - 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_saved_query_flattened_error(): - client = AssetServiceClient( - 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_saved_query( - asset_service.DeleteSavedQueryRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_saved_query_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_saved_query), - '__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_saved_query( - 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_saved_query_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_saved_query( - asset_service.DeleteSavedQueryRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.BatchGetEffectiveIamPoliciesRequest, - dict, -]) -def test_batch_get_effective_iam_policies(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.batch_get_effective_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.BatchGetEffectiveIamPoliciesResponse( - ) - response = client.batch_get_effective_iam_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.BatchGetEffectiveIamPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.BatchGetEffectiveIamPoliciesResponse) - - -def test_batch_get_effective_iam_policies_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 = AssetServiceClient( - 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.batch_get_effective_iam_policies), - '__call__') as call: - client.batch_get_effective_iam_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.BatchGetEffectiveIamPoliciesRequest() - -@pytest.mark.asyncio -async def test_batch_get_effective_iam_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.BatchGetEffectiveIamPoliciesRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.batch_get_effective_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetEffectiveIamPoliciesResponse( - )) - response = await client.batch_get_effective_iam_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.BatchGetEffectiveIamPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.BatchGetEffectiveIamPoliciesResponse) - - -@pytest.mark.asyncio -async def test_batch_get_effective_iam_policies_async_from_dict(): - await test_batch_get_effective_iam_policies_async(request_type=dict) - - -def test_batch_get_effective_iam_policies_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.BatchGetEffectiveIamPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_effective_iam_policies), - '__call__') as call: - call.return_value = asset_service.BatchGetEffectiveIamPoliciesResponse() - client.batch_get_effective_iam_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_batch_get_effective_iam_policies_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.BatchGetEffectiveIamPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_effective_iam_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.BatchGetEffectiveIamPoliciesResponse()) - await client.batch_get_effective_iam_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeOrgPoliciesRequest, - dict, -]) -def test_analyze_org_policies(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_org_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.analyze_org_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_analyze_org_policies_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 = AssetServiceClient( - 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.analyze_org_policies), - '__call__') as call: - client.analyze_org_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPoliciesRequest() - -@pytest.mark.asyncio -async def test_analyze_org_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeOrgPoliciesRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_org_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.analyze_org_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_analyze_org_policies_async_from_dict(): - await test_analyze_org_policies_async(request_type=dict) - - -def test_analyze_org_policies_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeOrgPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policies), - '__call__') as call: - call.return_value = asset_service.AnalyzeOrgPoliciesResponse() - client.analyze_org_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_analyze_org_policies_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeOrgPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPoliciesResponse()) - await client.analyze_org_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -def test_analyze_org_policies_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_org_policies( - scope='scope_value', - constraint='constraint_value', - filter='filter_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].constraint - mock_val = 'constraint_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - - -def test_analyze_org_policies_flattened_error(): - client = AssetServiceClient( - 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.analyze_org_policies( - asset_service.AnalyzeOrgPoliciesRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_analyze_org_policies_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_org_policies( - scope='scope_value', - constraint='constraint_value', - filter='filter_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].constraint - mock_val = 'constraint_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_analyze_org_policies_flattened_error_async(): - client = AssetServiceAsyncClient( - 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.analyze_org_policies( - asset_service.AnalyzeOrgPoliciesRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - - -def test_analyze_org_policies_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.analyze_org_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('scope', ''), - )), - ) - pager = client.analyze_org_policies(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult) - for i in results) -def test_analyze_org_policies_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.analyze_org_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - ), - RuntimeError, - ) - pages = list(client.analyze_org_policies(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_analyze_org_policies_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.analyze_org_policies(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, asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_analyze_org_policies_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.analyze_org_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeOrgPolicyGovernedContainersRequest, - dict, -]) -def test_analyze_org_policy_governed_containers(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_org_policy_governed_containers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - next_page_token='next_page_token_value', - ) - response = client.analyze_org_policy_governed_containers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPolicyGovernedContainersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedContainersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_analyze_org_policy_governed_containers_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 = AssetServiceClient( - 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.analyze_org_policy_governed_containers), - '__call__') as call: - client.analyze_org_policy_governed_containers() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPolicyGovernedContainersRequest() - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_containers_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeOrgPolicyGovernedContainersRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_org_policy_governed_containers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - next_page_token='next_page_token_value', - )) - response = await client.analyze_org_policy_governed_containers(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPolicyGovernedContainersRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedContainersAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_containers_async_from_dict(): - await test_analyze_org_policy_governed_containers_async(request_type=dict) - - -def test_analyze_org_policy_governed_containers_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_containers), - '__call__') as call: - call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() - client.analyze_org_policy_governed_containers(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_containers_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_containers), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedContainersResponse()) - await client.analyze_org_policy_governed_containers(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', - 'scope=scope_value', - ) in kw['metadata'] - - -def test_analyze_org_policy_governed_containers_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_containers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_org_policy_governed_containers( - scope='scope_value', - constraint='constraint_value', - filter='filter_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].constraint - mock_val = 'constraint_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - - -def test_analyze_org_policy_governed_containers_flattened_error(): - client = AssetServiceClient( - 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.analyze_org_policy_governed_containers( - asset_service.AnalyzeOrgPolicyGovernedContainersRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_containers_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_containers), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedContainersResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_org_policy_governed_containers( - scope='scope_value', - constraint='constraint_value', - filter='filter_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].constraint - mock_val = 'constraint_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_containers_flattened_error_async(): - client = AssetServiceAsyncClient( - 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.analyze_org_policy_governed_containers( - asset_service.AnalyzeOrgPolicyGovernedContainersRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - - -def test_analyze_org_policy_governed_containers_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.analyze_org_policy_governed_containers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('scope', ''), - )), - ) - pager = client.analyze_org_policy_governed_containers(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer) - for i in results) -def test_analyze_org_policy_governed_containers_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.analyze_org_policy_governed_containers), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - ), - RuntimeError, - ) - pages = list(client.analyze_org_policy_governed_containers(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_analyze_org_policy_governed_containers_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_containers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - ), - RuntimeError, - ) - async_pager = await client.analyze_org_policy_governed_containers(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, asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer) - for i in responses) - - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_containers_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_containers), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.analyze_org_policy_governed_containers(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, - dict, -]) -def test_analyze_org_policy_governed_assets(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_org_policy_governed_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - next_page_token='next_page_token_value', - ) - response = client.analyze_org_policy_governed_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_analyze_org_policy_governed_assets_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 = AssetServiceClient( - 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.analyze_org_policy_governed_assets), - '__call__') as call: - client.analyze_org_policy_governed_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.analyze_org_policy_governed_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.analyze_org_policy_governed_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_assets_async_from_dict(): - await test_analyze_org_policy_governed_assets_async(request_type=dict) - - -def test_analyze_org_policy_governed_assets_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_assets), - '__call__') as call: - call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() - client.analyze_org_policy_governed_assets(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_assets_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse()) - await client.analyze_org_policy_governed_assets(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', - 'scope=scope_value', - ) in kw['metadata'] - - -def test_analyze_org_policy_governed_assets_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.analyze_org_policy_governed_assets( - scope='scope_value', - constraint='constraint_value', - filter='filter_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].constraint - mock_val = 'constraint_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - - -def test_analyze_org_policy_governed_assets_flattened_error(): - client = AssetServiceClient( - 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.analyze_org_policy_governed_assets( - asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_assets_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.analyze_org_policy_governed_assets( - scope='scope_value', - constraint='constraint_value', - filter='filter_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].constraint - mock_val = 'constraint_value' - assert arg == mock_val - arg = args[0].filter - mock_val = 'filter_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_assets_flattened_error_async(): - client = AssetServiceAsyncClient( - 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.analyze_org_policy_governed_assets( - asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - - -def test_analyze_org_policy_governed_assets_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.analyze_org_policy_governed_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('scope', ''), - )), - ) - pager = client.analyze_org_policy_governed_assets(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset) - for i in results) -def test_analyze_org_policy_governed_assets_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.analyze_org_policy_governed_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - ), - RuntimeError, - ) - pages = list(client.analyze_org_policy_governed_assets(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_analyze_org_policy_governed_assets_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - ), - RuntimeError, - ) - async_pager = await client.analyze_org_policy_governed_assets(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, asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset) - for i in responses) - - -@pytest.mark.asyncio -async def test_analyze_org_policy_governed_assets_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.analyze_org_policy_governed_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.analyze_org_policy_governed_assets(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - asset_service.ExportAssetsRequest, - dict, -]) -def test_export_assets_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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.export_assets(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_export_assets_rest_required_fields(request_type=asset_service.ExportAssetsRequest): - transport_class = transports.AssetServiceRestTransport - - 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()).export_assets._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()).export_assets._get_unset_required_fields(jsonified_request) - 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 = AssetServiceClient( - 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.export_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_export_assets_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.export_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "outputConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_export_assets_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_export_assets") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_export_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.ExportAssetsRequest.pb(asset_service.ExportAssetsRequest()) - 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 = asset_service.ExportAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.export_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_export_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.ExportAssetsRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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.export_assets(request) - - -def test_export_assets_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.ListAssetsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_assets_rest_required_fields(request_type=asset_service.ListAssetsRequest): - transport_class = transports.AssetServiceRestTransport - - 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_assets._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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("asset_types", "content_type", "page_size", "page_token", "read_time", "relationship_types", )) - 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.ListAssetsResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("assetTypes", "contentType", "pageSize", "pageToken", "readTime", "relationshipTypes", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.ListAssetsRequest.pb(asset_service.ListAssetsRequest()) - 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 = asset_service.ListAssetsResponse.to_json(asset_service.ListAssetsResponse()) - - request = asset_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListAssetsRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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_assets(request) - - -def test_list_assets_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.ListAssetsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/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 - # Convert return value to protobuf type - return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_assets(**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=*/*}/assets" % client.transport._host, args[1]) - - -def test_list_assets_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_assets( - asset_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.ListAssetsResponse.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': 'sample1/sample2'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.Asset) - for i in results) - - pages = list(client.list_assets(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", [ - asset_service.BatchGetAssetsHistoryRequest, - dict, -]) -def test_batch_get_assets_history_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.BatchGetAssetsHistoryResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.BatchGetAssetsHistoryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_get_assets_history(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) - - -def test_batch_get_assets_history_rest_required_fields(request_type=asset_service.BatchGetAssetsHistoryRequest): - transport_class = transports.AssetServiceRestTransport - - 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()).batch_get_assets_history._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()).batch_get_assets_history._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("asset_names", "content_type", "read_time_window", "relationship_types", )) - 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.BatchGetAssetsHistoryResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.BatchGetAssetsHistoryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_get_assets_history(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_get_assets_history_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_get_assets_history._get_unset_required_fields({}) - assert set(unset_fields) == (set(("assetNames", "contentType", "readTimeWindow", "relationshipTypes", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_get_assets_history_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_batch_get_assets_history") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_batch_get_assets_history") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.BatchGetAssetsHistoryRequest.pb(asset_service.BatchGetAssetsHistoryRequest()) - 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 = asset_service.BatchGetAssetsHistoryResponse.to_json(asset_service.BatchGetAssetsHistoryResponse()) - - request = asset_service.BatchGetAssetsHistoryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.BatchGetAssetsHistoryResponse() - - client.batch_get_assets_history(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_get_assets_history_rest_bad_request(transport: str = 'rest', request_type=asset_service.BatchGetAssetsHistoryRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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.batch_get_assets_history(request) - - -def test_batch_get_assets_history_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.CreateFeedRequest, - dict, -]) -def test_create_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_feed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -def test_create_feed_rest_required_fields(request_type=asset_service.CreateFeedRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["feed_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()).create_feed._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["feedId"] = 'feed_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_feed._get_unset_required_fields(jsonified_request) - 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 "feedId" in jsonified_request - assert jsonified_request["feedId"] == 'feed_id_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.Feed() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "feedId", "feed", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_create_feed") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_create_feed") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.CreateFeedRequest.pb(asset_service.CreateFeedRequest()) - 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 = asset_service.Feed.to_json(asset_service.Feed()) - - request = asset_service.CreateFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.Feed() - - client.create_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.CreateFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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.create_feed(request) - - -def test_create_feed_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.Feed() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/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 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_feed(**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=*/*}/feeds" % client.transport._host, args[1]) - - -def test_create_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.CreateFeedRequest(), - parent='parent_value', - ) - - -def test_create_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.GetFeedRequest, - dict, -]) -def test_get_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_feed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -def test_get_feed_rest_required_fields(request_type=asset_service.GetFeedRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feed._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_feed._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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.Feed() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_get_feed") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_get_feed") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.GetFeedRequest.pb(asset_service.GetFeedRequest()) - 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 = asset_service.Feed.to_json(asset_service.Feed()) - - request = asset_service.GetFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.Feed() - - client.get_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.GetFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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_feed(request) - - -def test_get_feed_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.Feed() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'sample1/sample2/feeds/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 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_feed(**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=*/*/feeds/*}" % client.transport._host, args[1]) - - -def test_get_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.GetFeedRequest(), - name='name_value', - ) - - -def test_get_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListFeedsRequest, - dict, -]) -def test_list_feeds_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.ListFeedsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_feeds(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) - - -def test_list_feeds_rest_required_fields(request_type=asset_service.ListFeedsRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feeds._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_feeds._get_unset_required_fields(jsonified_request) - 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.ListFeedsResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_feeds(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_feeds_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_feeds._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_feeds_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_feeds") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_feeds") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.ListFeedsRequest.pb(asset_service.ListFeedsRequest()) - 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 = asset_service.ListFeedsResponse.to_json(asset_service.ListFeedsResponse()) - - request = asset_service.ListFeedsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.ListFeedsResponse() - - client.list_feeds(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_feeds_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListFeedsRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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_feeds(request) - - -def test_list_feeds_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.ListFeedsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/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 - # Convert return value to protobuf type - return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_feeds(**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=*/*}/feeds" % client.transport._host, args[1]) - - -def test_list_feeds_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feeds( - asset_service.ListFeedsRequest(), - parent='parent_value', - ) - - -def test_list_feeds_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.UpdateFeedRequest, - dict, -]) -def test_update_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'feed': {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - relationship_types=['relationship_types_value'], - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_feed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - assert response.relationship_types == ['relationship_types_value'] - - -def test_update_feed_rest_required_fields(request_type=asset_service.UpdateFeedRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feed._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_feed._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.Feed() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("feed", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_update_feed") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_update_feed") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.UpdateFeedRequest.pb(asset_service.UpdateFeedRequest()) - 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 = asset_service.Feed.to_json(asset_service.Feed()) - - request = asset_service.UpdateFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.Feed() - - client.update_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.UpdateFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'feed': {'name': 'sample1/sample2/feeds/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.update_feed(request) - - -def test_update_feed_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.Feed() - - # get arguments that satisfy an http rule for this method - sample_request = {'feed': {'name': 'sample1/sample2/feeds/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - feed=asset_service.Feed(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_feed(**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/{feed.name=*/*/feeds/*}" % client.transport._host, args[1]) - - -def test_update_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.UpdateFeedRequest(), - feed=asset_service.Feed(name='name_value'), - ) - - -def test_update_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.DeleteFeedRequest, - dict, -]) -def test_delete_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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_feed(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_feed_rest_required_fields(request_type=asset_service.DeleteFeedRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feed._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_feed._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 = AssetServiceClient( - 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_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "pre_delete_feed") as pre: - pre.assert_not_called() - pb_message = asset_service.DeleteFeedRequest.pb(asset_service.DeleteFeedRequest()) - 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 = asset_service.DeleteFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.DeleteFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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_feed(request) - - -def test_delete_feed_rest_flattened(): - client = AssetServiceClient( - 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': 'sample1/sample2/feeds/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_feed(**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=*/*/feeds/*}" % client.transport._host, args[1]) - - -def test_delete_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.DeleteFeedRequest(), - name='name_value', - ) - - -def test_delete_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.SearchAllResourcesRequest, - dict, -]) -def test_search_all_resources_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.SearchAllResourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_all_resources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_resources_rest_required_fields(request_type=asset_service.SearchAllResourcesRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - 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()).search_all_resources._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["scope"] = 'scope_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_resources._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("asset_types", "order_by", "page_size", "page_token", "query", "read_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.SearchAllResourcesResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search_all_resources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_all_resources_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_all_resources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("assetTypes", "orderBy", "pageSize", "pageToken", "query", "readMask", )) & set(("scope", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_all_resources_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_resources") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_resources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.SearchAllResourcesRequest.pb(asset_service.SearchAllResourcesRequest()) - 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 = asset_service.SearchAllResourcesResponse.to_json(asset_service.SearchAllResourcesResponse()) - - request = asset_service.SearchAllResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.SearchAllResourcesResponse() - - client.search_all_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_all_resources_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllResourcesRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.search_all_resources(request) - - -def test_search_all_resources_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.SearchAllResourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'scope': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_all_resources(**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/{scope=*/*}:searchAllResources" % client.transport._host, args[1]) - - -def test_search_all_resources_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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.search_all_resources( - asset_service.SearchAllResourcesRequest(), - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - - -def test_search_all_resources_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.ResourceSearchResult(), - assets.ResourceSearchResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.SearchAllResourcesResponse.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 = {'scope': 'sample1/sample2'} - - pager = client.search_all_resources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.ResourceSearchResult) - for i in results) - - pages = list(client.search_all_resources(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", [ - asset_service.SearchAllIamPoliciesRequest, - dict, -]) -def test_search_all_iam_policies_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.SearchAllIamPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_all_iam_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_iam_policies_rest_required_fields(request_type=asset_service.SearchAllIamPoliciesRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - 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()).search_all_iam_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["scope"] = 'scope_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_iam_policies._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("asset_types", "order_by", "page_size", "page_token", "query", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.SearchAllIamPoliciesResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search_all_iam_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_all_iam_policies_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_all_iam_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("assetTypes", "orderBy", "pageSize", "pageToken", "query", )) & set(("scope", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_all_iam_policies_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_iam_policies") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_iam_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.SearchAllIamPoliciesRequest.pb(asset_service.SearchAllIamPoliciesRequest()) - 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 = asset_service.SearchAllIamPoliciesResponse.to_json(asset_service.SearchAllIamPoliciesResponse()) - - request = asset_service.SearchAllIamPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.SearchAllIamPoliciesResponse() - - client.search_all_iam_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_all_iam_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllIamPoliciesRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.search_all_iam_policies(request) - - -def test_search_all_iam_policies_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.SearchAllIamPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'scope': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - scope='scope_value', - query='query_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_all_iam_policies(**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/{scope=*/*}:searchAllIamPolicies" % client.transport._host, args[1]) - - -def test_search_all_iam_policies_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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.search_all_iam_policies( - asset_service.SearchAllIamPoliciesRequest(), - scope='scope_value', - query='query_value', - ) - - -def test_search_all_iam_policies_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.SearchAllIamPoliciesResponse.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 = {'scope': 'sample1/sample2'} - - pager = client.search_all_iam_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.IamPolicySearchResult) - for i in results) - - pages = list(client.search_all_iam_policies(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", [ - asset_service.AnalyzeIamPolicyRequest, - dict, -]) -def test_analyze_iam_policy_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'analysis_query': {'scope': 'sample1/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 = asset_service.AnalyzeIamPolicyResponse( - fully_explored=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.analyze_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) - assert response.fully_explored is True - - -def test_analyze_iam_policy_rest_required_fields(request_type=asset_service.AnalyzeIamPolicyRequest): - transport_class = transports.AssetServiceRestTransport - - 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()).analyze_iam_policy._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()).analyze_iam_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("analysis_query", "execution_timeout", "saved_analysis_query", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.AnalyzeIamPolicyResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.analyze_iam_policy(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_iam_policy_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("analysisQuery", "executionTimeout", "savedAnalysisQuery", )) & set(("analysisQuery", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_iam_policy_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_iam_policy") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_iam_policy") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.AnalyzeIamPolicyRequest.pb(asset_service.AnalyzeIamPolicyRequest()) - 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 = asset_service.AnalyzeIamPolicyResponse.to_json(asset_service.AnalyzeIamPolicyResponse()) - - request = asset_service.AnalyzeIamPolicyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.AnalyzeIamPolicyResponse() - - client.analyze_iam_policy(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_iam_policy_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeIamPolicyRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'analysis_query': {'scope': 'sample1/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.analyze_iam_policy(request) - - -def test_analyze_iam_policy_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeIamPolicyLongrunningRequest, - dict, -]) -def test_analyze_iam_policy_longrunning_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'analysis_query': {'scope': 'sample1/sample2'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # 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.analyze_iam_policy_longrunning(request) - - # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" - - -def test_analyze_iam_policy_longrunning_rest_required_fields(request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): - transport_class = transports.AssetServiceRestTransport - - 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()).analyze_iam_policy_longrunning._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()).analyze_iam_policy_longrunning._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AssetServiceClient( - 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.analyze_iam_policy_longrunning(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_iam_policy_longrunning_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_iam_policy_longrunning._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("analysisQuery", "outputConfig", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_iam_policy_longrunning_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_iam_policy_longrunning") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_iam_policy_longrunning") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.AnalyzeIamPolicyLongrunningRequest.pb(asset_service.AnalyzeIamPolicyLongrunningRequest()) - 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 = asset_service.AnalyzeIamPolicyLongrunningRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.analyze_iam_policy_longrunning(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_iam_policy_longrunning_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'analysis_query': {'scope': 'sample1/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.analyze_iam_policy_longrunning(request) - - -def test_analyze_iam_policy_longrunning_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeMoveRequest, - dict, -]) -def test_analyze_move_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'sample1/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 = asset_service.AnalyzeMoveResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeMoveResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.analyze_move(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeMoveResponse) - - -def test_analyze_move_rest_required_fields(request_type=asset_service.AnalyzeMoveRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["resource"] = "" - request_init["destination_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 - assert "destinationParent" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_move._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "destinationParent" in jsonified_request - assert jsonified_request["destinationParent"] == request_init["destination_parent"] - - jsonified_request["resource"] = 'resource_value' - jsonified_request["destinationParent"] = 'destination_parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_move._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("destination_parent", "view", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == 'resource_value' - assert "destinationParent" in jsonified_request - assert jsonified_request["destinationParent"] == 'destination_parent_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.AnalyzeMoveResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.AnalyzeMoveResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.analyze_move(request) - - expected_params = [ - ( - "destinationParent", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_move_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_move._get_unset_required_fields({}) - assert set(unset_fields) == (set(("destinationParent", "view", )) & set(("resource", "destinationParent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_move_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_move") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_move") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.AnalyzeMoveRequest.pb(asset_service.AnalyzeMoveRequest()) - 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 = asset_service.AnalyzeMoveResponse.to_json(asset_service.AnalyzeMoveResponse()) - - request = asset_service.AnalyzeMoveRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.AnalyzeMoveResponse() - - client.analyze_move(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_move_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeMoveRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'resource': 'sample1/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.analyze_move(request) - - -def test_analyze_move_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.QueryAssetsRequest, - dict, -]) -def test_query_assets_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.QueryAssetsResponse( - job_reference='job_reference_value', - done=True, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.QueryAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.query_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.QueryAssetsResponse) - assert response.job_reference == 'job_reference_value' - assert response.done is True - - -def test_query_assets_rest_required_fields(request_type=asset_service.QueryAssetsRequest): - transport_class = transports.AssetServiceRestTransport - - 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()).query_assets._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()).query_assets._get_unset_required_fields(jsonified_request) - 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.QueryAssetsResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.QueryAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.query_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_query_assets_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.query_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_query_assets_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_query_assets") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_query_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.QueryAssetsRequest.pb(asset_service.QueryAssetsRequest()) - 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 = asset_service.QueryAssetsResponse.to_json(asset_service.QueryAssetsResponse()) - - request = asset_service.QueryAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.QueryAssetsResponse() - - client.query_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_query_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.QueryAssetsRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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.query_assets(request) - - -def test_query_assets_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.CreateSavedQueryRequest, - dict, -]) -def test_create_saved_query_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/sample2'} - request_init["saved_query"] = {'name': 'name_value', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'creator': 'creator_value', 'last_update_time': {}, 'last_updater': 'last_updater_value', 'labels': {}, 'content': {'iam_policy_analysis_query': {'scope': 'scope_value', 'resource_selector': {'full_resource_name': 'full_resource_name_value'}, 'identity_selector': {'identity': 'identity_value'}, 'access_selector': {'roles': ['roles_value1', 'roles_value2'], 'permissions': ['permissions_value1', 'permissions_value2']}, 'options': {'expand_groups': True, 'expand_roles': True, 'expand_resources': True, 'output_resource_edges': True, 'output_group_edges': True, 'analyze_service_account_impersonation': True}, 'condition_context': {'access_time': {}}}}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = asset_service.CreateSavedQueryRequest.meta.fields["saved_query"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - else: - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - for field, value in request_init["saved_query"].items(): - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - for subfield_to_delete in subfields_not_in_runtime: - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["saved_query"][field])): - del request_init["saved_query"][field][i][subfield] - else: - del request_init["saved_query"][field][subfield] - 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 = asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_saved_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -def test_create_saved_query_rest_required_fields(request_type=asset_service.CreateSavedQueryRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["saved_query_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 "savedQueryId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_saved_query._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "savedQueryId" in jsonified_request - assert jsonified_request["savedQueryId"] == request_init["saved_query_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["savedQueryId"] = 'saved_query_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_saved_query._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("saved_query_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 "savedQueryId" in jsonified_request - assert jsonified_request["savedQueryId"] == 'saved_query_id_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.SavedQuery() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_saved_query(request) - - expected_params = [ - ( - "savedQueryId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_saved_query_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_saved_query._get_unset_required_fields({}) - assert set(unset_fields) == (set(("savedQueryId", )) & set(("parent", "savedQuery", "savedQueryId", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_saved_query_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_create_saved_query") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_create_saved_query") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.CreateSavedQueryRequest.pb(asset_service.CreateSavedQueryRequest()) - 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 = asset_service.SavedQuery.to_json(asset_service.SavedQuery()) - - request = asset_service.CreateSavedQueryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.SavedQuery() - - client.create_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.CreateSavedQueryRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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.create_saved_query(request) - - -def test_create_saved_query_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.SavedQuery() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - saved_query=asset_service.SavedQuery(name='name_value'), - saved_query_id='saved_query_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_saved_query(**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=*/*}/savedQueries" % client.transport._host, args[1]) - - -def test_create_saved_query_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_saved_query( - asset_service.CreateSavedQueryRequest(), - parent='parent_value', - saved_query=asset_service.SavedQuery(name='name_value'), - saved_query_id='saved_query_id_value', - ) - - -def test_create_saved_query_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.GetSavedQueryRequest, - dict, -]) -def test_get_saved_query_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/savedQueries/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 = asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_saved_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -def test_get_saved_query_rest_required_fields(request_type=asset_service.GetSavedQueryRequest): - transport_class = transports.AssetServiceRestTransport - - 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_saved_query._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_saved_query._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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.SavedQuery() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_saved_query(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_saved_query_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_saved_query._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_saved_query_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_get_saved_query") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_get_saved_query") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.GetSavedQueryRequest.pb(asset_service.GetSavedQueryRequest()) - 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 = asset_service.SavedQuery.to_json(asset_service.SavedQuery()) - - request = asset_service.GetSavedQueryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.SavedQuery() - - client.get_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.GetSavedQueryRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/savedQueries/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_saved_query(request) - - -def test_get_saved_query_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.SavedQuery() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'sample1/sample2/savedQueries/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 - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_saved_query(**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=*/*/savedQueries/*}" % client.transport._host, args[1]) - - -def test_get_saved_query_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_saved_query( - asset_service.GetSavedQueryRequest(), - name='name_value', - ) - - -def test_get_saved_query_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListSavedQueriesRequest, - dict, -]) -def test_list_saved_queries_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.ListSavedQueriesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.ListSavedQueriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_saved_queries(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSavedQueriesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_saved_queries_rest_required_fields(request_type=asset_service.ListSavedQueriesRequest): - transport_class = transports.AssetServiceRestTransport - - 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_saved_queries._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_saved_queries._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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.ListSavedQueriesResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.ListSavedQueriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_saved_queries(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_saved_queries_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_saved_queries._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_saved_queries_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_saved_queries") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_saved_queries") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.ListSavedQueriesRequest.pb(asset_service.ListSavedQueriesRequest()) - 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 = asset_service.ListSavedQueriesResponse.to_json(asset_service.ListSavedQueriesResponse()) - - request = asset_service.ListSavedQueriesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.ListSavedQueriesResponse() - - client.list_saved_queries(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_saved_queries_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListSavedQueriesRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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_saved_queries(request) - - -def test_list_saved_queries_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.ListSavedQueriesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/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 - # Convert return value to protobuf type - return_value = asset_service.ListSavedQueriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_saved_queries(**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=*/*}/savedQueries" % client.transport._host, args[1]) - - -def test_list_saved_queries_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_saved_queries( - asset_service.ListSavedQueriesRequest(), - parent='parent_value', - ) - - -def test_list_saved_queries_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - next_page_token='abc', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[], - next_page_token='def', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - ], - next_page_token='ghi', - ), - asset_service.ListSavedQueriesResponse( - saved_queries=[ - asset_service.SavedQuery(), - asset_service.SavedQuery(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.ListSavedQueriesResponse.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': 'sample1/sample2'} - - pager = client.list_saved_queries(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.SavedQuery) - for i in results) - - pages = list(client.list_saved_queries(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", [ - asset_service.UpdateSavedQueryRequest, - dict, -]) -def test_update_saved_query_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'saved_query': {'name': 'sample1/sample2/savedQueries/sample3'}} - request_init["saved_query"] = {'name': 'sample1/sample2/savedQueries/sample3', 'description': 'description_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'creator': 'creator_value', 'last_update_time': {}, 'last_updater': 'last_updater_value', 'labels': {}, 'content': {'iam_policy_analysis_query': {'scope': 'scope_value', 'resource_selector': {'full_resource_name': 'full_resource_name_value'}, 'identity_selector': {'identity': 'identity_value'}, 'access_selector': {'roles': ['roles_value1', 'roles_value2'], 'permissions': ['permissions_value1', 'permissions_value2']}, 'options': {'expand_groups': True, 'expand_roles': True, 'expand_resources': True, 'output_resource_edges': True, 'output_group_edges': True, 'analyze_service_account_impersonation': True}, 'condition_context': {'access_time': {}}}}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = asset_service.UpdateSavedQueryRequest.meta.fields["saved_query"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - else: - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - for field, value in request_init["saved_query"].items(): - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - for subfield_to_delete in subfields_not_in_runtime: - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["saved_query"][field])): - del request_init["saved_query"][field][i][subfield] - else: - del request_init["saved_query"][field][subfield] - 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 = asset_service.SavedQuery( - name='name_value', - description='description_value', - creator='creator_value', - last_updater='last_updater_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_saved_query(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.SavedQuery) - assert response.name == 'name_value' - assert response.description == 'description_value' - assert response.creator == 'creator_value' - assert response.last_updater == 'last_updater_value' - - -def test_update_saved_query_rest_required_fields(request_type=asset_service.UpdateSavedQueryRequest): - transport_class = transports.AssetServiceRestTransport - - 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_saved_query._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_saved_query._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("update_mask", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.SavedQuery() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_saved_query(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_saved_query_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_saved_query._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("savedQuery", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_saved_query_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_update_saved_query") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_update_saved_query") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.UpdateSavedQueryRequest.pb(asset_service.UpdateSavedQueryRequest()) - 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 = asset_service.SavedQuery.to_json(asset_service.SavedQuery()) - - request = asset_service.UpdateSavedQueryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.SavedQuery() - - client.update_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.UpdateSavedQueryRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'saved_query': {'name': 'sample1/sample2/savedQueries/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.update_saved_query(request) - - -def test_update_saved_query_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.SavedQuery() - - # get arguments that satisfy an http rule for this method - sample_request = {'saved_query': {'name': 'sample1/sample2/savedQueries/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - saved_query=asset_service.SavedQuery(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_saved_query(**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/{saved_query.name=*/*/savedQueries/*}" % client.transport._host, args[1]) - - -def test_update_saved_query_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_saved_query( - asset_service.UpdateSavedQueryRequest(), - saved_query=asset_service.SavedQuery(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_saved_query_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.DeleteSavedQueryRequest, - dict, -]) -def test_delete_saved_query_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/savedQueries/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_saved_query(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_saved_query_rest_required_fields(request_type=asset_service.DeleteSavedQueryRequest): - transport_class = transports.AssetServiceRestTransport - - 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_saved_query._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_saved_query._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 = AssetServiceClient( - 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_saved_query(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_saved_query_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_saved_query._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_saved_query_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "pre_delete_saved_query") as pre: - pre.assert_not_called() - pb_message = asset_service.DeleteSavedQueryRequest.pb(asset_service.DeleteSavedQueryRequest()) - 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 = asset_service.DeleteSavedQueryRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_saved_query(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_saved_query_rest_bad_request(transport: str = 'rest', request_type=asset_service.DeleteSavedQueryRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/savedQueries/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_saved_query(request) - - -def test_delete_saved_query_rest_flattened(): - client = AssetServiceClient( - 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': 'sample1/sample2/savedQueries/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_saved_query(**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=*/*/savedQueries/*}" % client.transport._host, args[1]) - - -def test_delete_saved_query_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_saved_query( - asset_service.DeleteSavedQueryRequest(), - name='name_value', - ) - - -def test_delete_saved_query_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.BatchGetEffectiveIamPoliciesRequest, - dict, -]) -def test_batch_get_effective_iam_policies_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.BatchGetEffectiveIamPoliciesResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.batch_get_effective_iam_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.BatchGetEffectiveIamPoliciesResponse) - - -def test_batch_get_effective_iam_policies_rest_required_fields(request_type=asset_service.BatchGetEffectiveIamPoliciesRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - request_init["names"] = "" - 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 "names" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_get_effective_iam_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "names" in jsonified_request - assert jsonified_request["names"] == request_init["names"] - - jsonified_request["scope"] = 'scope_value' - jsonified_request["names"] = 'names_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).batch_get_effective_iam_policies._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("names", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - assert "names" in jsonified_request - assert jsonified_request["names"] == 'names_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.BatchGetEffectiveIamPoliciesResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.batch_get_effective_iam_policies(request) - - expected_params = [ - ( - "names", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_batch_get_effective_iam_policies_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.batch_get_effective_iam_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("names", )) & set(("scope", "names", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_get_effective_iam_policies_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_batch_get_effective_iam_policies") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_batch_get_effective_iam_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.BatchGetEffectiveIamPoliciesRequest.pb(asset_service.BatchGetEffectiveIamPoliciesRequest()) - 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 = asset_service.BatchGetEffectiveIamPoliciesResponse.to_json(asset_service.BatchGetEffectiveIamPoliciesResponse()) - - request = asset_service.BatchGetEffectiveIamPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.BatchGetEffectiveIamPoliciesResponse() - - client.batch_get_effective_iam_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_get_effective_iam_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.BatchGetEffectiveIamPoliciesRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.batch_get_effective_iam_policies(request) - - -def test_batch_get_effective_iam_policies_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.AnalyzeOrgPoliciesRequest, - dict, -]) -def test_analyze_org_policies_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.AnalyzeOrgPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.analyze_org_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_analyze_org_policies_rest_required_fields(request_type=asset_service.AnalyzeOrgPoliciesRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - request_init["constraint"] = "" - 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 "constraint" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "constraint" in jsonified_request - assert jsonified_request["constraint"] == request_init["constraint"] - - jsonified_request["scope"] = 'scope_value' - jsonified_request["constraint"] = 'constraint_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policies._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("constraint", "filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - assert "constraint" in jsonified_request - assert jsonified_request["constraint"] == 'constraint_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.AnalyzeOrgPoliciesResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.analyze_org_policies(request) - - expected_params = [ - ( - "constraint", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_org_policies_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_org_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("constraint", "filter", "pageSize", "pageToken", )) & set(("scope", "constraint", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_org_policies_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_org_policies") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_org_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.AnalyzeOrgPoliciesRequest.pb(asset_service.AnalyzeOrgPoliciesRequest()) - 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 = asset_service.AnalyzeOrgPoliciesResponse.to_json(asset_service.AnalyzeOrgPoliciesResponse()) - - request = asset_service.AnalyzeOrgPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.AnalyzeOrgPoliciesResponse() - - client.analyze_org_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_org_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeOrgPoliciesRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.analyze_org_policies(request) - - -def test_analyze_org_policies_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.AnalyzeOrgPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'scope': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.analyze_org_policies(**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/{scope=*/*}:analyzeOrgPolicies" % client.transport._host, args[1]) - - -def test_analyze_org_policies_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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.analyze_org_policies( - asset_service.AnalyzeOrgPoliciesRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - - -def test_analyze_org_policies_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPoliciesResponse( - org_policy_results=[ - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.AnalyzeOrgPoliciesResponse.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 = {'scope': 'sample1/sample2'} - - pager = client.analyze_org_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.AnalyzeOrgPoliciesResponse.OrgPolicyResult) - for i in results) - - pages = list(client.analyze_org_policies(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", [ - asset_service.AnalyzeOrgPolicyGovernedContainersRequest, - dict, -]) -def test_analyze_org_policy_governed_containers_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.analyze_org_policy_governed_containers(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedContainersPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_analyze_org_policy_governed_containers_rest_required_fields(request_type=asset_service.AnalyzeOrgPolicyGovernedContainersRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - request_init["constraint"] = "" - 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 "constraint" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_containers._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "constraint" in jsonified_request - assert jsonified_request["constraint"] == request_init["constraint"] - - jsonified_request["scope"] = 'scope_value' - jsonified_request["constraint"] = 'constraint_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_containers._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("constraint", "filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - assert "constraint" in jsonified_request - assert jsonified_request["constraint"] == 'constraint_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.analyze_org_policy_governed_containers(request) - - expected_params = [ - ( - "constraint", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_org_policy_governed_containers_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_org_policy_governed_containers._get_unset_required_fields({}) - assert set(unset_fields) == (set(("constraint", "filter", "pageSize", "pageToken", )) & set(("scope", "constraint", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_org_policy_governed_containers_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_org_policy_governed_containers") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_org_policy_governed_containers") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.AnalyzeOrgPolicyGovernedContainersRequest.pb(asset_service.AnalyzeOrgPolicyGovernedContainersRequest()) - 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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.to_json(asset_service.AnalyzeOrgPolicyGovernedContainersResponse()) - - request = asset_service.AnalyzeOrgPolicyGovernedContainersRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() - - client.analyze_org_policy_governed_containers(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_org_policy_governed_containers_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeOrgPolicyGovernedContainersRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.analyze_org_policy_governed_containers(request) - - -def test_analyze_org_policy_governed_containers_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.AnalyzeOrgPolicyGovernedContainersResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'scope': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.analyze_org_policy_governed_containers(**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/{scope=*/*}:analyzeOrgPolicyGovernedContainers" % client.transport._host, args[1]) - - -def test_analyze_org_policy_governed_containers_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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.analyze_org_policy_governed_containers( - asset_service.AnalyzeOrgPolicyGovernedContainersRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - - -def test_analyze_org_policy_governed_containers_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse( - governed_containers=[ - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.AnalyzeOrgPolicyGovernedContainersResponse.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 = {'scope': 'sample1/sample2'} - - pager = client.analyze_org_policy_governed_containers(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedContainersResponse.GovernedContainer) - for i in results) - - pages = list(client.analyze_org_policy_governed_containers(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", [ - asset_service.AnalyzeOrgPolicyGovernedAssetsRequest, - dict, -]) -def test_analyze_org_policy_governed_assets_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.analyze_org_policy_governed_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AnalyzeOrgPolicyGovernedAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_analyze_org_policy_governed_assets_rest_required_fields(request_type=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - request_init["constraint"] = "" - 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 "constraint" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_assets._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "constraint" in jsonified_request - assert jsonified_request["constraint"] == request_init["constraint"] - - jsonified_request["scope"] = 'scope_value' - jsonified_request["constraint"] = 'constraint_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).analyze_org_policy_governed_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("constraint", "filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - assert "constraint" in jsonified_request - assert jsonified_request["constraint"] == 'constraint_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.analyze_org_policy_governed_assets(request) - - expected_params = [ - ( - "constraint", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_analyze_org_policy_governed_assets_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.analyze_org_policy_governed_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("constraint", "filter", "pageSize", "pageToken", )) & set(("scope", "constraint", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_analyze_org_policy_governed_assets_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_analyze_org_policy_governed_assets") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_analyze_org_policy_governed_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest.pb(asset_service.AnalyzeOrgPolicyGovernedAssetsRequest()) - 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.to_json(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse()) - - request = asset_service.AnalyzeOrgPolicyGovernedAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() - - client.analyze_org_policy_governed_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_analyze_org_policy_governed_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.AnalyzeOrgPolicyGovernedAssetsRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.analyze_org_policy_governed_assets(request) - - -def test_analyze_org_policy_governed_assets_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'scope': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.analyze_org_policy_governed_assets(**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/{scope=*/*}:analyzeOrgPolicyGovernedAssets" % client.transport._host, args[1]) - - -def test_analyze_org_policy_governed_assets_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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.analyze_org_policy_governed_assets( - asset_service.AnalyzeOrgPolicyGovernedAssetsRequest(), - scope='scope_value', - constraint='constraint_value', - filter='filter_value', - ) - - -def test_analyze_org_policy_governed_assets_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='abc', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[], - next_page_token='def', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - next_page_token='ghi', - ), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse( - governed_assets=[ - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.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 = {'scope': 'sample1/sample2'} - - pager = client.analyze_org_policy_governed_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.GovernedAsset) - for i in results) - - pages = list(client.analyze_org_policy_governed_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AssetServiceClient( - 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 = AssetServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AssetServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, -]) -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 = AssetServiceClient.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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AssetServiceGrpcTransport, - ) - -def test_asset_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_asset_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'export_assets', - 'list_assets', - 'batch_get_assets_history', - 'create_feed', - 'get_feed', - 'list_feeds', - 'update_feed', - 'delete_feed', - 'search_all_resources', - 'search_all_iam_policies', - 'analyze_iam_policy', - 'analyze_iam_policy_longrunning', - 'analyze_move', - 'query_assets', - 'create_saved_query', - 'get_saved_query', - 'list_saved_queries', - 'update_saved_query', - 'delete_saved_query', - 'batch_get_effective_iam_policies', - 'analyze_org_policies', - 'analyze_org_policy_governed_containers', - 'analyze_org_policy_governed_assets', - 'get_operation', - ) - 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_asset_service_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.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport( - 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_asset_service_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.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport() - adc.assert_called_once() - - -def test_asset_service_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) - AssetServiceClient() - 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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( - 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_asset_service_rest_lro_client(): - client = AssetServiceClient( - 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_asset_service_host_no_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_asset_service_host_with_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_asset_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AssetServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AssetServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.export_assets._session - session2 = client2.transport.export_assets._session - assert session1 != session2 - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 - session1 = client1.transport.batch_get_assets_history._session - session2 = client2.transport.batch_get_assets_history._session - assert session1 != session2 - session1 = client1.transport.create_feed._session - session2 = client2.transport.create_feed._session - assert session1 != session2 - session1 = client1.transport.get_feed._session - session2 = client2.transport.get_feed._session - assert session1 != session2 - session1 = client1.transport.list_feeds._session - session2 = client2.transport.list_feeds._session - assert session1 != session2 - session1 = client1.transport.update_feed._session - session2 = client2.transport.update_feed._session - assert session1 != session2 - session1 = client1.transport.delete_feed._session - session2 = client2.transport.delete_feed._session - assert session1 != session2 - session1 = client1.transport.search_all_resources._session - session2 = client2.transport.search_all_resources._session - assert session1 != session2 - session1 = client1.transport.search_all_iam_policies._session - session2 = client2.transport.search_all_iam_policies._session - assert session1 != session2 - session1 = client1.transport.analyze_iam_policy._session - session2 = client2.transport.analyze_iam_policy._session - assert session1 != session2 - session1 = client1.transport.analyze_iam_policy_longrunning._session - session2 = client2.transport.analyze_iam_policy_longrunning._session - assert session1 != session2 - session1 = client1.transport.analyze_move._session - session2 = client2.transport.analyze_move._session - assert session1 != session2 - session1 = client1.transport.query_assets._session - session2 = client2.transport.query_assets._session - assert session1 != session2 - session1 = client1.transport.create_saved_query._session - session2 = client2.transport.create_saved_query._session - assert session1 != session2 - session1 = client1.transport.get_saved_query._session - session2 = client2.transport.get_saved_query._session - assert session1 != session2 - session1 = client1.transport.list_saved_queries._session - session2 = client2.transport.list_saved_queries._session - assert session1 != session2 - session1 = client1.transport.update_saved_query._session - session2 = client2.transport.update_saved_query._session - assert session1 != session2 - session1 = client1.transport.delete_saved_query._session - session2 = client2.transport.delete_saved_query._session - assert session1 != session2 - session1 = client1.transport.batch_get_effective_iam_policies._session - session2 = client2.transport.batch_get_effective_iam_policies._session - assert session1 != session2 - session1 = client1.transport.analyze_org_policies._session - session2 = client2.transport.analyze_org_policies._session - assert session1 != session2 - session1 = client1.transport.analyze_org_policy_governed_containers._session - session2 = client2.transport.analyze_org_policy_governed_containers._session - assert session1 != session2 - session1 = client1.transport.analyze_org_policy_governed_assets._session - session2 = client2.transport.analyze_org_policy_governed_assets._session - assert session1 != session2 -def test_asset_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcTransport( - 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_asset_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcAsyncIOTransport( - 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_asset_service_grpc_lro_client(): - client = AssetServiceClient( - 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_asset_service_grpc_lro_async_client(): - client = AssetServiceAsyncClient( - 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_access_level_path(): - access_policy = "squid" - access_level = "clam" - expected = "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) - actual = AssetServiceClient.access_level_path(access_policy, access_level) - assert expected == actual - - -def test_parse_access_level_path(): - expected = { - "access_policy": "whelk", - "access_level": "octopus", - } - path = AssetServiceClient.access_level_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_access_level_path(path) - assert expected == actual - -def test_access_policy_path(): - access_policy = "oyster" - expected = "accessPolicies/{access_policy}".format(access_policy=access_policy, ) - actual = AssetServiceClient.access_policy_path(access_policy) - assert expected == actual - - -def test_parse_access_policy_path(): - expected = { - "access_policy": "nudibranch", - } - path = AssetServiceClient.access_policy_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_access_policy_path(path) - assert expected == actual - -def test_asset_path(): - expected = "*".format() - actual = AssetServiceClient.asset_path() - assert expected == actual - - -def test_parse_asset_path(): - expected = { - } - path = AssetServiceClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_asset_path(path) - assert expected == actual - -def test_feed_path(): - project = "cuttlefish" - feed = "mussel" - expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) - actual = AssetServiceClient.feed_path(project, feed) - assert expected == actual - - -def test_parse_feed_path(): - expected = { - "project": "winkle", - "feed": "nautilus", - } - path = AssetServiceClient.feed_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_feed_path(path) - assert expected == actual - -def test_inventory_path(): - project = "scallop" - location = "abalone" - instance = "squid" - expected = "projects/{project}/locations/{location}/instances/{instance}/inventory".format(project=project, location=location, instance=instance, ) - actual = AssetServiceClient.inventory_path(project, location, instance) - assert expected == actual - - -def test_parse_inventory_path(): - expected = { - "project": "clam", - "location": "whelk", - "instance": "octopus", - } - path = AssetServiceClient.inventory_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_inventory_path(path) - assert expected == actual - -def test_saved_query_path(): - project = "oyster" - saved_query = "nudibranch" - expected = "projects/{project}/savedQueries/{saved_query}".format(project=project, saved_query=saved_query, ) - actual = AssetServiceClient.saved_query_path(project, saved_query) - assert expected == actual - - -def test_parse_saved_query_path(): - expected = { - "project": "cuttlefish", - "saved_query": "mussel", - } - path = AssetServiceClient.saved_query_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_saved_query_path(path) - assert expected == actual - -def test_service_perimeter_path(): - access_policy = "winkle" - service_perimeter = "nautilus" - expected = "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) - actual = AssetServiceClient.service_perimeter_path(access_policy, service_perimeter) - assert expected == actual - - -def test_parse_service_perimeter_path(): - expected = { - "access_policy": "scallop", - "service_perimeter": "abalone", - } - path = AssetServiceClient.service_perimeter_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_service_perimeter_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AssetServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AssetServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = AssetServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AssetServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AssetServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AssetServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = AssetServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AssetServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AssetServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AssetServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( - 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_operation_rest_bad_request(transport: str = 'rest', request_type=operations_pb2.GetOperationRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - request = request_type() - request = json_format.ParseDict({'name': 'sample1/sample2/operations/sample3/sample4'}, 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request_init = {'name': 'sample1/sample2/operations/sample3/sample4'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # 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_get_operation(transport: str = "grpc"): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = AssetServiceClient( - 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 = AssetServiceAsyncClient( - 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_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AssetServiceClient( - 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 = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), -]) -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/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc deleted file mode 100644 index 801f6d8a..00000000 --- a/owl-bot-staging/v1p1beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py - google/cloud/asset/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/v1p1beta1/.flake8 b/owl-bot-staging/v1p1beta1/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v1p1beta1/.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/v1p1beta1/MANIFEST.in b/owl-bot-staging/v1p1beta1/MANIFEST.in deleted file mode 100644 index 165ea472..00000000 --- a/owl-bot-staging/v1p1beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/asset *.py -recursive-include google/cloud/asset_v1p1beta1 *.py diff --git a/owl-bot-staging/v1p1beta1/README.rst b/owl-bot-staging/v1p1beta1/README.rst deleted file mode 100644 index 110d4086..00000000 --- a/owl-bot-staging/v1p1beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Asset 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 Asset 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/v1p1beta1/docs/_static/custom.css b/owl-bot-staging/v1p1beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0..00000000 --- a/owl-bot-staging/v1p1beta1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst deleted file mode 100644 index c034bc69..00000000 --- a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/asset_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -AssetService ------------------------------- - -.. automodule:: google.cloud.asset_v1p1beta1.services.asset_service - :members: - :inherited-members: - -.. automodule:: google.cloud.asset_v1p1beta1.services.asset_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst deleted file mode 100644 index 2839e354..00000000 --- a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Asset v1p1beta1 API -============================================= -.. toctree:: - :maxdepth: 2 - - asset_service diff --git a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst deleted file mode 100644 index 0df91774..00000000 --- a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Asset v1p1beta1 API -========================================== - -.. automodule:: google.cloud.asset_v1p1beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1p1beta1/docs/conf.py b/owl-bot-staging/v1p1beta1/docs/conf.py deleted file mode 100644 index b6b4f094..00000000 --- a/owl-bot-staging/v1p1beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-asset 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-asset" -copyright = u"2023, 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 = 'en' - -# 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-asset-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-asset.tex", - u"google-cloud-asset 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-asset", - u"Google Cloud Asset 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-asset", - u"google-cloud-asset Documentation", - author, - "google-cloud-asset", - "GAPIC library for Google Cloud Asset 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/v1p1beta1/docs/index.rst b/owl-bot-staging/v1p1beta1/docs/index.rst deleted file mode 100644 index e52b7a52..00000000 --- a/owl-bot-staging/v1p1beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - asset_v1p1beta1/services - asset_v1p1beta1/types diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py deleted file mode 100644 index ea3f160c..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.asset_v1p1beta1.services.asset_service.client import AssetServiceClient -from google.cloud.asset_v1p1beta1.services.asset_service.async_client import AssetServiceAsyncClient - -from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllIamPoliciesRequest -from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllIamPoliciesResponse -from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllResourcesRequest -from google.cloud.asset_v1p1beta1.types.asset_service import SearchAllResourcesResponse -from google.cloud.asset_v1p1beta1.types.assets import IamPolicySearchResult -from google.cloud.asset_v1p1beta1.types.assets import Permissions -from google.cloud.asset_v1p1beta1.types.assets import StandardResourceMetadata - -__all__ = ('AssetServiceClient', - 'AssetServiceAsyncClient', - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'IamPolicySearchResult', - 'Permissions', - 'StandardResourceMetadata', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py deleted file mode 100644 index ad399661..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset_v1p1beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.asset_service import AssetServiceClient -from .services.asset_service import AssetServiceAsyncClient - -from .types.asset_service import SearchAllIamPoliciesRequest -from .types.asset_service import SearchAllIamPoliciesResponse -from .types.asset_service import SearchAllResourcesRequest -from .types.asset_service import SearchAllResourcesResponse -from .types.assets import IamPolicySearchResult -from .types.assets import Permissions -from .types.assets import StandardResourceMetadata - -__all__ = ( - 'AssetServiceAsyncClient', -'AssetServiceClient', -'IamPolicySearchResult', -'Permissions', -'SearchAllIamPoliciesRequest', -'SearchAllIamPoliciesResponse', -'SearchAllResourcesRequest', -'SearchAllResourcesResponse', -'StandardResourceMetadata', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json deleted file mode 100644 index c8f50c01..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_metadata.json +++ /dev/null @@ -1,58 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.asset_v1p1beta1", - "protoPackage": "google.cloud.asset.v1p1beta1", - "schema": "1.0", - "services": { - "AssetService": { - "clients": { - "grpc": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AssetServiceAsyncClient", - "rpcs": { - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - } - } - }, - "rest": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py deleted file mode 100644 index 89a37dc9..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py deleted file mode 100644 index 542f923f..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AssetServiceClient -from .async_client import AssetServiceAsyncClient - -__all__ = ( - 'AssetServiceClient', - 'AssetServiceAsyncClient', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py deleted file mode 100644 index 83ca1005..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,494 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.asset_v1p1beta1 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.cloud.asset_v1p1beta1.services.asset_service import pagers -from google.cloud.asset_v1p1beta1.types import asset_service -from google.cloud.asset_v1p1beta1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .client import AssetServiceClient - - -class AssetServiceAsyncClient: - """Asset service definition.""" - - _client: AssetServiceClient - - DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT - - common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AssetServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AssetServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AssetServiceClient.common_project_path) - parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) - common_location_path = staticmethod(AssetServiceClient.common_location_path) - parse_common_location_path = staticmethod(AssetServiceClient.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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def search_all_resources(self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesAsyncPager: - r"""Searches all the resources within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - resources within a scope, even if they don't have ``.get`` - permission of all the resources. Callers should have - ``cloud.assets.SearchAllResources`` permission on the requested - scope, otherwise the request will be rejected. - - .. 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 asset_v1p1beta1 - - async def sample_search_all_resources(): - # Create a client - client = asset_v1p1beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest, dict]]): - The request object. Search all resources request. - scope (:class:`str`): - Required. The relative name of an asset. The search is - limited to the resources within the ``scope``. The - allowed value must be: - - - Organization number (such as "organizations/123") - - Folder number (such as "folders/1234") - - Project number (such as "projects/12345") - - Project ID (such as "projects/abc") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`str`): - Optional. The query statement. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - asset_types (:class:`MutableSequence[str]`): - Optional. A list of asset types that - this request searches for. If empty, it - will search all the supported asset - types. - - This corresponds to the ``asset_types`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesAsyncPager: - Search all resources response. - - 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([scope, query, asset_types]) - 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 = asset_service.SearchAllResourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - if asset_types: - request.asset_types.extend(asset_types) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_all_resources, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.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(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllResourcesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_all_iam_policies(self, - request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllIamPoliciesAsyncPager: - r"""Searches all the IAM policies within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - IAM policies within a scope, even if they don't have - ``.getIamPolicy`` permission of all the IAM policies. Callers - should have ``cloud.assets.SearchAllIamPolicies`` permission on - the requested scope, otherwise the request will be rejected. - - .. 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 asset_v1p1beta1 - - async def sample_search_all_iam_policies(): - # Create a client - client = asset_v1p1beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest, dict]]): - The request object. Search all IAM policies request. - scope (:class:`str`): - Required. The relative name of an asset. The search is - limited to the resources within the ``scope``. The - allowed value must be: - - - Organization number (such as "organizations/123") - - Folder number (such as "folders/1234") - - Project number (such as "projects/12345") - - Project ID (such as "projects/abc") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (:class:`str`): - Optional. The query statement. Examples: - - - "policy:myuser@mydomain.com" - - "policy:(myuser@mydomain.com viewer)" - - This corresponds to the ``query`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager: - Search all IAM policies response. - - 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([scope, query]) - 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 = asset_service.SearchAllIamPoliciesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_all_iam_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.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(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllIamPoliciesAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "AssetServiceAsyncClient": - 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__ = ( - "AssetServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py deleted file mode 100644 index 09df402f..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py +++ /dev/null @@ -1,679 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.asset_v1p1beta1 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.cloud.asset_v1p1beta1.services.asset_service import pagers -from google.cloud.asset_v1p1beta1.types import asset_service -from google.cloud.asset_v1p1beta1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .transports.rest import AssetServiceRestTransport - - -class AssetServiceClientMeta(type): - """Metaclass for the AssetService 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[AssetServiceTransport]] - _transport_registry["grpc"] = AssetServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AssetServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AssetServiceTransport]: - """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 AssetServiceClient(metaclass=AssetServiceClientMeta): - """Asset service definition.""" - - @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 = "cloudasset.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: - AssetServiceClient: 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: - AssetServiceClient: 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) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @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, AssetServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): - # transport is a AssetServiceTransport 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 search_all_resources(self, - request: Optional[Union[asset_service.SearchAllResourcesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - asset_types: Optional[MutableSequence[str]] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesPager: - r"""Searches all the resources within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - resources within a scope, even if they don't have ``.get`` - permission of all the resources. Callers should have - ``cloud.assets.SearchAllResources`` permission on the requested - scope, otherwise the request will be rejected. - - .. 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 asset_v1p1beta1 - - def sample_search_all_resources(): - # Create a client - client = asset_v1p1beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest, dict]): - The request object. Search all resources request. - scope (str): - Required. The relative name of an asset. The search is - limited to the resources within the ``scope``. The - allowed value must be: - - - Organization number (such as "organizations/123") - - Folder number (such as "folders/1234") - - Project number (such as "projects/12345") - - Project ID (such as "projects/abc") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (str): - Optional. The query statement. - This corresponds to the ``query`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - asset_types (MutableSequence[str]): - Optional. A list of asset types that - this request searches for. If empty, it - will search all the supported asset - types. - - This corresponds to the ``asset_types`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesPager: - Search all resources response. - - 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([scope, query, asset_types]) - 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 asset_service.SearchAllResourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.SearchAllResourcesRequest): - request = asset_service.SearchAllResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - if asset_types is not None: - request.asset_types = asset_types - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_all_resources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllResourcesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def search_all_iam_policies(self, - request: Optional[Union[asset_service.SearchAllIamPoliciesRequest, dict]] = None, - *, - scope: Optional[str] = None, - query: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllIamPoliciesPager: - r"""Searches all the IAM policies within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - IAM policies within a scope, even if they don't have - ``.getIamPolicy`` permission of all the IAM policies. Callers - should have ``cloud.assets.SearchAllIamPolicies`` permission on - the requested scope, otherwise the request will be rejected. - - .. 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 asset_v1p1beta1 - - def sample_search_all_iam_policies(): - # Create a client - client = asset_v1p1beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest, dict]): - The request object. Search all IAM policies request. - scope (str): - Required. The relative name of an asset. The search is - limited to the resources within the ``scope``. The - allowed value must be: - - - Organization number (such as "organizations/123") - - Folder number (such as "folders/1234") - - Project number (such as "projects/12345") - - Project ID (such as "projects/abc") - - This corresponds to the ``scope`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - query (str): - Optional. The query statement. Examples: - - - "policy:myuser@mydomain.com" - - "policy:(myuser@mydomain.com viewer)" - - This corresponds to the ``query`` 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.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesPager: - Search all IAM policies response. - - 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([scope, query]) - 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 asset_service.SearchAllIamPoliciesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): - request = asset_service.SearchAllIamPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if scope is not None: - request.scope = scope - if query is not None: - request.query = query - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_all_iam_policies] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("scope", request.scope), - )), - ) - - # 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.SearchAllIamPoliciesPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AssetServiceClient": - 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() - - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AssetServiceClient", -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py deleted file mode 100644 index d8499278..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py +++ /dev/null @@ -1,261 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.asset_v1p1beta1.types import asset_service -from google.cloud.asset_v1p1beta1.types import assets - - -class SearchAllResourcesPager: - """A pager for iterating through ``search_all_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchAllResources`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` - 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[..., asset_service.SearchAllResourcesResponse], - request: asset_service.SearchAllResourcesRequest, - response: asset_service.SearchAllResourcesResponse, - *, - 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.asset_v1p1beta1.types.SearchAllResourcesRequest): - The initial request object. - response (google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse): - 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 = asset_service.SearchAllResourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.SearchAllResourcesResponse]: - 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[assets.StandardResourceMetadata]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAllResourcesAsyncPager: - """A pager for iterating through ``search_all_resources`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchAllResources`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse` - 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[asset_service.SearchAllResourcesResponse]], - request: asset_service.SearchAllResourcesRequest, - response: asset_service.SearchAllResourcesResponse, - *, - 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.asset_v1p1beta1.types.SearchAllResourcesRequest): - The initial request object. - response (google.cloud.asset_v1p1beta1.types.SearchAllResourcesResponse): - 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 = asset_service.SearchAllResourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.SearchAllResourcesResponse]: - 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[assets.StandardResourceMetadata]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAllIamPoliciesPager: - """A pager for iterating through ``search_all_iam_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchAllIamPolicies`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` - 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[..., asset_service.SearchAllIamPoliciesResponse], - request: asset_service.SearchAllIamPoliciesRequest, - response: asset_service.SearchAllIamPoliciesResponse, - *, - 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.asset_v1p1beta1.types.SearchAllIamPoliciesRequest): - The initial request object. - response (google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse): - 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 = asset_service.SearchAllIamPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.SearchAllIamPoliciesResponse]: - 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[assets.IamPolicySearchResult]: - for page in self.pages: - yield from page.results - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class SearchAllIamPoliciesAsyncPager: - """A pager for iterating through ``search_all_iam_policies`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchAllIamPolicies`` requests and continue to iterate - through the ``results`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse` - 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[asset_service.SearchAllIamPoliciesResponse]], - request: asset_service.SearchAllIamPoliciesRequest, - response: asset_service.SearchAllIamPoliciesResponse, - *, - 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.asset_v1p1beta1.types.SearchAllIamPoliciesRequest): - The initial request object. - response (google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesResponse): - 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 = asset_service.SearchAllIamPoliciesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.SearchAllIamPoliciesResponse]: - 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[assets.IamPolicySearchResult]: - async def async_generator(): - async for page in self.pages: - for response in page.results: - 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/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py deleted file mode 100644 index c34a5f8f..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AssetServiceTransport -from .grpc import AssetServiceGrpcTransport -from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .rest import AssetServiceRestTransport -from .rest import AssetServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AssetServiceRestTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', - 'AssetServiceRestTransport', - 'AssetServiceRestInterceptor', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py deleted file mode 100644 index 0af6e37c..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,177 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.asset_v1p1beta1 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.cloud.asset_v1p1beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AssetServiceTransport(abc.ABC): - """Abstract transport class for AssetService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudasset.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.search_all_resources: gapic_v1.method.wrap_method( - self.search_all_resources, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=client_info, - ), - self.search_all_iam_policies: gapic_v1.method.wrap_method( - self.search_all_iam_policies, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.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 search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - Union[ - asset_service.SearchAllResourcesResponse, - Awaitable[asset_service.SearchAllResourcesResponse] - ]]: - raise NotImplementedError() - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - Union[ - asset_service.SearchAllIamPoliciesResponse, - Awaitable[asset_service.SearchAllIamPoliciesResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AssetServiceTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py deleted file mode 100644 index ddb025c0..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,303 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.cloud.asset_v1p1beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO - - -class AssetServiceGrpcTransport(AssetServiceTransport): - """gRPC backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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 search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - asset_service.SearchAllResourcesResponse]: - r"""Return a callable for the search all resources method over gRPC. - - Searches all the resources within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - resources within a scope, even if they don't have ``.get`` - permission of all the resources. Callers should have - ``cloud.assets.SearchAllResources`` permission on the requested - scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllResourcesRequest], - ~.SearchAllResourcesResponse]: - 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 'search_all_resources' not in self._stubs: - self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources', - request_serializer=asset_service.SearchAllResourcesRequest.serialize, - response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, - ) - return self._stubs['search_all_resources'] - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - asset_service.SearchAllIamPoliciesResponse]: - r"""Return a callable for the search all iam policies method over gRPC. - - Searches all the IAM policies within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - IAM policies within a scope, even if they don't have - ``.getIamPolicy`` permission of all the IAM policies. Callers - should have ``cloud.assets.SearchAllIamPolicies`` permission on - the requested scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllIamPoliciesRequest], - ~.SearchAllIamPoliciesResponse]: - 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 'search_all_iam_policies' not in self._stubs: - self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies', - request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, - response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, - ) - return self._stubs['search_all_iam_policies'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AssetServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py deleted file mode 100644 index 2801d4b7..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.cloud.asset_v1p1beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AssetServiceGrpcTransport - - -class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): - """gRPC AsyncIO backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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 search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - Awaitable[asset_service.SearchAllResourcesResponse]]: - r"""Return a callable for the search all resources method over gRPC. - - Searches all the resources within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - resources within a scope, even if they don't have ``.get`` - permission of all the resources. Callers should have - ``cloud.assets.SearchAllResources`` permission on the requested - scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllResourcesRequest], - Awaitable[~.SearchAllResourcesResponse]]: - 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 'search_all_resources' not in self._stubs: - self._stubs['search_all_resources'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p1beta1.AssetService/SearchAllResources', - request_serializer=asset_service.SearchAllResourcesRequest.serialize, - response_deserializer=asset_service.SearchAllResourcesResponse.deserialize, - ) - return self._stubs['search_all_resources'] - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - Awaitable[asset_service.SearchAllIamPoliciesResponse]]: - r"""Return a callable for the search all iam policies method over gRPC. - - Searches all the IAM policies within a given accessible Resource - Manager scope (project/folder/organization). This RPC gives - callers especially administrators the ability to search all the - IAM policies within a scope, even if they don't have - ``.getIamPolicy`` permission of all the IAM policies. Callers - should have ``cloud.assets.SearchAllIamPolicies`` permission on - the requested scope, otherwise the request will be rejected. - - Returns: - Callable[[~.SearchAllIamPoliciesRequest], - Awaitable[~.SearchAllIamPoliciesResponse]]: - 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 'search_all_iam_policies' not in self._stubs: - self._stubs['search_all_iam_policies'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p1beta1.AssetService/SearchAllIamPolicies', - request_serializer=asset_service.SearchAllIamPoliciesRequest.serialize, - response_deserializer=asset_service.SearchAllIamPoliciesResponse.deserialize, - ) - return self._stubs['search_all_iam_policies'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py deleted file mode 100644 index e76c75c3..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/rest.py +++ /dev/null @@ -1,399 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -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 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.asset_v1p1beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: - """Interceptor for AssetService. - - 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 AssetServiceRestTransport. - - .. code-block:: python - class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): - def pre_search_all_iam_policies(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_all_iam_policies(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_search_all_resources(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_all_resources(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) - client = AssetServiceClient(transport=transport) - - - """ - def pre_search_all_iam_policies(self, request: asset_service.SearchAllIamPoliciesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllIamPoliciesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_all_iam_policies - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_search_all_iam_policies(self, response: asset_service.SearchAllIamPoliciesResponse) -> asset_service.SearchAllIamPoliciesResponse: - """Post-rpc interceptor for search_all_iam_policies - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_search_all_resources(self, request: asset_service.SearchAllResourcesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.SearchAllResourcesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_all_resources - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_search_all_resources(self, response: asset_service.SearchAllResourcesResponse) -> asset_service.SearchAllResourcesResponse: - """Post-rpc interceptor for search_all_resources - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AssetServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AssetServiceRestInterceptor - - -class AssetServiceRestTransport(AssetServiceTransport): - """REST backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _SearchAllIamPolicies(AssetServiceRestStub): - def __hash__(self): - return hash("SearchAllIamPolicies") - - __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: asset_service.SearchAllIamPoliciesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.SearchAllIamPoliciesResponse: - r"""Call the search all iam policies method over HTTP. - - Args: - request (~.asset_service.SearchAllIamPoliciesRequest): - The request object. Search all IAM policies request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.SearchAllIamPoliciesResponse: - Search all IAM policies response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{scope=*/*}/iamPolicies:searchAll', - }, - ] - request, metadata = self._interceptor.pre_search_all_iam_policies(request, metadata) - pb_request = asset_service.SearchAllIamPoliciesRequest.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 = asset_service.SearchAllIamPoliciesResponse() - pb_resp = asset_service.SearchAllIamPoliciesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_all_iam_policies(resp) - return resp - - class _SearchAllResources(AssetServiceRestStub): - def __hash__(self): - return hash("SearchAllResources") - - __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: asset_service.SearchAllResourcesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.SearchAllResourcesResponse: - r"""Call the search all resources method over HTTP. - - Args: - request (~.asset_service.SearchAllResourcesRequest): - The request object. Search all resources request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.SearchAllResourcesResponse: - Search all resources response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p1beta1/{scope=*/*}/resources:searchAll', - }, - ] - request, metadata = self._interceptor.pre_search_all_resources(request, metadata) - pb_request = asset_service.SearchAllResourcesRequest.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 = asset_service.SearchAllResourcesResponse() - pb_resp = asset_service.SearchAllResourcesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_all_resources(resp) - return resp - - @property - def search_all_iam_policies(self) -> Callable[ - [asset_service.SearchAllIamPoliciesRequest], - asset_service.SearchAllIamPoliciesResponse]: - # 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._SearchAllIamPolicies(self._session, self._host, self._interceptor) # type: ignore - - @property - def search_all_resources(self) -> Callable[ - [asset_service.SearchAllResourcesRequest], - asset_service.SearchAllResourcesResponse]: - # 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._SearchAllResources(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AssetServiceRestTransport', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py deleted file mode 100644 index 6053b9ff..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .asset_service import ( - SearchAllIamPoliciesRequest, - SearchAllIamPoliciesResponse, - SearchAllResourcesRequest, - SearchAllResourcesResponse, -) -from .assets import ( - IamPolicySearchResult, - Permissions, - StandardResourceMetadata, -) - -__all__ = ( - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'IamPolicySearchResult', - 'Permissions', - 'StandardResourceMetadata', -) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py deleted file mode 100644 index 3d5c996a..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py +++ /dev/null @@ -1,212 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.asset_v1p1beta1.types import assets - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p1beta1', - manifest={ - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - }, -) - - -class SearchAllResourcesRequest(proto.Message): - r"""Search all resources request. - - Attributes: - scope (str): - Required. The relative name of an asset. The search is - limited to the resources within the ``scope``. The allowed - value must be: - - - Organization number (such as "organizations/123") - - Folder number (such as "folders/1234") - - Project number (such as "projects/12345") - - Project ID (such as "projects/abc") - query (str): - Optional. The query statement. - asset_types (MutableSequence[str]): - Optional. A list of asset types that this - request searches for. If empty, it will search - all the supported asset types. - page_size (int): - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If - set to zero, server will pick an appropriate default. - Returned results may be fewer than requested. When this - happens, there could be more results as long as - ``next_page_token`` is returned. - page_token (str): - Optional. If present, then retrieve the next batch of - results from the preceding call to this method. - ``page_token`` must be the value of ``next_page_token`` from - the previous response. The values of all other method - parameters, must be identical to those in the previous call. - order_by (str): - Optional. A comma separated list of fields specifying the - sorting order of the results. The default order is - ascending. Add ``DESC`` after the field name to indicate - descending order. Redundant space characters are ignored. - For example, ``location DESC , name``. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - page_size: int = proto.Field( - proto.INT32, - number=4, - ) - page_token: str = proto.Field( - proto.STRING, - number=5, - ) - order_by: str = proto.Field( - proto.STRING, - number=10, - ) - - -class SearchAllResourcesResponse(proto.Message): - r"""Search all resources response. - - Attributes: - results (MutableSequence[google.cloud.asset_v1p1beta1.types.StandardResourceMetadata]): - A list of resource that match the search - query. - next_page_token (str): - If there are more results than those appearing in this - response, then ``next_page_token`` is included. To get the - next set of results, call this method again using the value - of ``next_page_token`` as ``page_token``. - """ - - @property - def raw_page(self): - return self - - results: MutableSequence[assets.StandardResourceMetadata] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=assets.StandardResourceMetadata, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -class SearchAllIamPoliciesRequest(proto.Message): - r"""Search all IAM policies request. - - Attributes: - scope (str): - Required. The relative name of an asset. The search is - limited to the resources within the ``scope``. The allowed - value must be: - - - Organization number (such as "organizations/123") - - Folder number (such as "folders/1234") - - Project number (such as "projects/12345") - - Project ID (such as "projects/abc") - query (str): - Optional. The query statement. Examples: - - - "policy:myuser@mydomain.com" - - "policy:(myuser@mydomain.com viewer)". - page_size (int): - Optional. The page size for search result pagination. Page - size is capped at 500 even if a larger value is given. If - set to zero, server will pick an appropriate default. - Returned results may be fewer than requested. When this - happens, there could be more results as long as - ``next_page_token`` is returned. - page_token (str): - Optional. If present, retrieve the next batch of results - from the preceding call to this method. ``page_token`` must - be the value of ``next_page_token`` from the previous - response. The values of all other method parameters must be - identical to those in the previous call. - """ - - scope: str = proto.Field( - proto.STRING, - number=1, - ) - query: str = proto.Field( - proto.STRING, - number=2, - ) - page_size: int = proto.Field( - proto.INT32, - number=3, - ) - page_token: str = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchAllIamPoliciesResponse(proto.Message): - r"""Search all IAM policies response. - - Attributes: - results (MutableSequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult]): - A list of IAM policies that match the search - query. Related information such as the - associated resource is returned along with the - policy. - next_page_token (str): - Set if there are more results than those appearing in this - response; to get the next set of results, call this method - again, using this value as the ``page_token``. - """ - - @property - def raw_page(self): - return self - - results: MutableSequence[assets.IamPolicySearchResult] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=assets.IamPolicySearchResult, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py deleted file mode 100644 index 28a1077f..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py +++ /dev/null @@ -1,203 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.iam.v1 import policy_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p1beta1', - manifest={ - 'StandardResourceMetadata', - 'IamPolicySearchResult', - 'Permissions', - }, -) - - -class StandardResourceMetadata(proto.Message): - r"""The standard metadata of a cloud resource. - - Attributes: - name (str): - The full resource name. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Resource - Names `__ - for more information. - asset_type (str): - The type of this resource. - For example: "compute.googleapis.com/Disk". - project (str): - The project that this resource belongs to, in the form of - ``projects/{project_number}``. - display_name (str): - The display name of this resource. - description (str): - One or more paragraphs of text description of - this resource. Maximum length could be up to 1M - bytes. - additional_attributes (MutableSequence[str]): - Additional searchable attributes of this - resource. Informational only. The exact set of - attributes is subject to change. For example: - project id, DNS name etc. - location (str): - Location can be "global", regional like - "us-east1", or zonal like "us-west1-b". - labels (MutableMapping[str, str]): - Labels associated with this resource. See `Labelling and - grouping Google Cloud - resources `__ - for more information. - network_tags (MutableSequence[str]): - Network tags associated with this resource. Like labels, - network tags are a type of annotations used to group Google - Cloud resources. See `Labelling Google Cloud - resources `__ - for more information. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - asset_type: str = proto.Field( - proto.STRING, - number=2, - ) - project: str = proto.Field( - proto.STRING, - number=3, - ) - display_name: str = proto.Field( - proto.STRING, - number=4, - ) - description: str = proto.Field( - proto.STRING, - number=5, - ) - additional_attributes: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - location: str = proto.Field( - proto.STRING, - number=11, - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - network_tags: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=13, - ) - - -class IamPolicySearchResult(proto.Message): - r"""The result for an IAM policy search. - - Attributes: - resource (str): - The `full resource - name `__ - of the resource associated with this IAM policy. - project (str): - The project that the associated Google Cloud resource - belongs to, in the form of ``projects/{project_number}``. If - an IAM policy is set on a resource -- such as a Compute - Engine instance or a Cloud Storage bucket -- the project - field will indicate the project that contains the resource. - If an IAM policy is set on a folder or orgnization, the - project field will be empty. - policy (google.iam.v1.policy_pb2.Policy): - The IAM policy attached to the specified - resource. Note that the original IAM policy can - contain multiple bindings. This only contains - the bindings that match the given query. For - queries that don't contain a constraint on - policies (e.g. an empty query), this contains - all the bindings. - explanation (google.cloud.asset_v1p1beta1.types.IamPolicySearchResult.Explanation): - Explanation about the IAM policy search - result. It contains additional information that - explains why the search result matches the - query. - """ - - class Explanation(proto.Message): - r"""Explanation about the IAM policy search result. - - Attributes: - matched_permissions (MutableMapping[str, google.cloud.asset_v1p1beta1.types.Permissions]): - The map from roles to their included permission matching the - permission query (e.g. containing - ``policy.role.permissions:``). Example role string: - "roles/compute.instanceAdmin". The roles can also be found - in the returned ``policy`` bindings. Note that the map is - populated only if requesting with a permission query. - """ - - matched_permissions: MutableMapping[str, 'Permissions'] = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='Permissions', - ) - - resource: str = proto.Field( - proto.STRING, - number=1, - ) - project: str = proto.Field( - proto.STRING, - number=3, - ) - policy: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - explanation: Explanation = proto.Field( - proto.MESSAGE, - number=5, - message=Explanation, - ) - - -class Permissions(proto.Message): - r"""IAM permissions. - - Attributes: - permissions (MutableSequence[str]): - A list of permissions. Example permission - string: "compute.disk.get". - """ - - permissions: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p1beta1/mypy.ini b/owl-bot-staging/v1p1beta1/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/owl-bot-staging/v1p1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1p1beta1/noxfile.py b/owl-bot-staging/v1p1beta1/noxfile.py deleted file mode 100644 index b9d4c480..00000000 --- a/owl-bot-staging/v1p1beta1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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/asset_v1p1beta1/', - '--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==7.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/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py deleted file mode 100644 index eeab16da..00000000 --- a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllIamPolicies -# 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-asset - - -# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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 asset_v1p1beta1 - - -async def sample_search_all_iam_policies(): - # Create a client - client = asset_v1p1beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_async] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py deleted file mode 100644 index 1198c482..00000000 --- a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllIamPolicies -# 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-asset - - -# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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 asset_v1p1beta1 - - -def sample_search_all_iam_policies(): - # Create a client - client = asset_v1p1beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllIamPoliciesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_iam_policies(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_sync] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py deleted file mode 100644 index 173f0087..00000000 --- a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllResources -# 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-asset - - -# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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 asset_v1p1beta1 - - -async def sample_search_all_resources(): - # Create a client - client = asset_v1p1beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_async] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py b/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py deleted file mode 100644 index fe079175..00000000 --- a/owl-bot-staging/v1p1beta1/samples/generated_samples/cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchAllResources -# 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-asset - - -# [START cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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 asset_v1p1beta1 - - -def sample_search_all_resources(): - # Create a client - client = asset_v1p1beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p1beta1.SearchAllResourcesRequest( - scope="scope_value", - ) - - # Make the request - page_result = client.search_all_resources(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_sync] diff --git a/owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json b/owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json deleted file mode 100644 index dcbeb822..00000000 --- a/owl-bot-staging/v1p1beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p1beta1.json +++ /dev/null @@ -1,361 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.asset.v1p1beta1", - "version": "v1p1beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-asset", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient.search_all_iam_policies", - "method": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllIamPolicies", - "service": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllIamPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesAsyncPager", - "shortName": "search_all_iam_policies" - }, - "description": "Sample for SearchAllIamPolicies", - "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient.search_all_iam_policies", - "method": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllIamPolicies", - "service": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllIamPolicies" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllIamPoliciesPager", - "shortName": "search_all_iam_policies" - }, - "description": "Sample for SearchAllIamPolicies", - "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllIamPolicies_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_iam_policies_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceAsyncClient.search_all_resources", - "method": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllResources", - "service": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "asset_types", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesAsyncPager", - "shortName": "search_all_resources" - }, - "description": "Sample for SearchAllResources", - "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p1beta1.AssetServiceClient.search_all_resources", - "method": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService.SearchAllResources", - "service": { - "fullName": "google.cloud.asset.v1p1beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "SearchAllResources" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest" - }, - { - "name": "scope", - "type": "str" - }, - { - "name": "query", - "type": "str" - }, - { - "name": "asset_types", - "type": "MutableSequence[str]" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1p1beta1.services.asset_service.pagers.SearchAllResourcesPager", - "shortName": "search_all_resources" - }, - "description": "Sample for SearchAllResources", - "file": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p1beta1_generated_AssetService_SearchAllResources_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": "cloudasset_v1p1beta1_generated_asset_service_search_all_resources_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py b/owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py deleted file mode 100644 index 1846c478..00000000 --- a/owl-bot-staging/v1p1beta1/scripts/fixup_asset_v1p1beta1_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 assetCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), - 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), - } - - 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=assetCallTransformer(), -): - """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 asset 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/v1p1beta1/setup.py b/owl-bot-staging/v1p1beta1/setup.py deleted file mode 100644 index 166120b0..00000000 --- a/owl-bot-staging/v1p1beta1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-asset' - - -description = "Google Cloud Asset API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/asset/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-asset" - -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/v1p1beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf99..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1p1beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p1beta1/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/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py deleted file mode 100644 index 3100699e..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py +++ /dev/null @@ -1,2674 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 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.asset_v1p1beta1.services.asset_service import AssetServiceAsyncClient -from google.cloud.asset_v1p1beta1.services.asset_service import AssetServiceClient -from google.cloud.asset_v1p1beta1.services.asset_service import pagers -from google.cloud.asset_v1p1beta1.services.asset_service import transports -from google.cloud.asset_v1p1beta1.types import asset_service -from google.cloud.asset_v1p1beta1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -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 AssetServiceClient._get_default_mtls_endpoint(None) is None - assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceRestTransport, - ] - assert transport in available_transports - - transport = AssetServiceClient.get_transport_class("grpc") - assert transport == transports.AssetServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_asset_service_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", [ - AssetServiceClient, AssetServiceAsyncClient -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), -]) -def test_asset_service_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_asset_service_client_client_options_from_dict(): - with mock.patch('google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.SearchAllResourcesRequest, - dict, -]) -def test_search_all_resources(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllResourcesResponse( - next_page_token='next_page_token_value', - ) - response = client.search_all_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_resources_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 = AssetServiceClient( - 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.search_all_resources), - '__call__') as call: - client.search_all_resources() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() - -@pytest.mark.asyncio -async def test_search_all_resources_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllResourcesRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_all_resources(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_all_resources_async_from_dict(): - await test_search_all_resources_async(request_type=dict) - - -def test_search_all_resources_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllResourcesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - call.return_value = asset_service.SearchAllResourcesResponse() - client.search_all_resources(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_all_resources_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllResourcesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) - await client.search_all_resources(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', - 'scope=scope_value', - ) in kw['metadata'] - - -def test_search_all_resources_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllResourcesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_all_resources( - scope='scope_value', - query='query_value', - asset_types=['asset_types_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - arg = args[0].asset_types - mock_val = ['asset_types_value'] - assert arg == mock_val - - -def test_search_all_resources_flattened_error(): - client = AssetServiceClient( - 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.search_all_resources( - asset_service.SearchAllResourcesRequest(), - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - -@pytest.mark.asyncio -async def test_search_all_resources_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllResourcesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllResourcesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_all_resources( - scope='scope_value', - query='query_value', - asset_types=['asset_types_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - arg = args[0].asset_types - mock_val = ['asset_types_value'] - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_all_resources_flattened_error_async(): - client = AssetServiceAsyncClient( - 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.search_all_resources( - asset_service.SearchAllResourcesRequest(), - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - - -def test_search_all_resources_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('scope', ''), - )), - ) - pager = client.search_all_resources(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.StandardResourceMetadata) - for i in results) -def test_search_all_resources_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_resources), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - ), - RuntimeError, - ) - pages = list(client.search_all_resources(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_search_all_resources_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_all_resources(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, assets.StandardResourceMetadata) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_all_resources_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_resources), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search_all_resources(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - asset_service.SearchAllIamPoliciesRequest, - dict, -]) -def test_search_all_iam_policies(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllIamPoliciesResponse( - next_page_token='next_page_token_value', - ) - response = client.search_all_iam_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_iam_policies_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 = AssetServiceClient( - 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.search_all_iam_policies), - '__call__') as call: - client.search_all_iam_policies() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() - -@pytest.mark.asyncio -async def test_search_all_iam_policies_async(transport: str = 'grpc_asyncio', request_type=asset_service.SearchAllIamPoliciesRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse( - next_page_token='next_page_token_value', - )) - response = await client.search_all_iam_policies(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_search_all_iam_policies_async_from_dict(): - await test_search_all_iam_policies_async(request_type=dict) - - -def test_search_all_iam_policies_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllIamPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - call.return_value = asset_service.SearchAllIamPoliciesResponse() - client.search_all_iam_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_search_all_iam_policies_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.SearchAllIamPoliciesRequest() - - request.scope = 'scope_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) - await client.search_all_iam_policies(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', - 'scope=scope_value', - ) in kw['metadata'] - - -def test_search_all_iam_policies_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllIamPoliciesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.search_all_iam_policies( - scope='scope_value', - query='query_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - - -def test_search_all_iam_policies_flattened_error(): - client = AssetServiceClient( - 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.search_all_iam_policies( - asset_service.SearchAllIamPoliciesRequest(), - scope='scope_value', - query='query_value', - ) - -@pytest.mark.asyncio -async def test_search_all_iam_policies_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.SearchAllIamPoliciesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.SearchAllIamPoliciesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.search_all_iam_policies( - scope='scope_value', - query='query_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].scope - mock_val = 'scope_value' - assert arg == mock_val - arg = args[0].query - mock_val = 'query_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_search_all_iam_policies_flattened_error_async(): - client = AssetServiceAsyncClient( - 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.search_all_iam_policies( - asset_service.SearchAllIamPoliciesRequest(), - scope='scope_value', - query='query_value', - ) - - -def test_search_all_iam_policies_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_iam_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('scope', ''), - )), - ) - pager = client.search_all_iam_policies(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.IamPolicySearchResult) - for i in results) -def test_search_all_iam_policies_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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.search_all_iam_policies), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - pages = list(client.search_all_iam_policies(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_search_all_iam_policies_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - async_pager = await client.search_all_iam_policies(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, assets.IamPolicySearchResult) - for i in responses) - - -@pytest.mark.asyncio -async def test_search_all_iam_policies_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_all_iam_policies), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search_all_iam_policies(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - asset_service.SearchAllResourcesRequest, - dict, -]) -def test_search_all_resources_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.SearchAllResourcesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_all_resources(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_resources_rest_required_fields(request_type=asset_service.SearchAllResourcesRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - 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()).search_all_resources._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["scope"] = 'scope_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_resources._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("asset_types", "order_by", "page_size", "page_token", "query", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.SearchAllResourcesResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search_all_resources(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_all_resources_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_all_resources._get_unset_required_fields({}) - assert set(unset_fields) == (set(("assetTypes", "orderBy", "pageSize", "pageToken", "query", )) & set(("scope", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_all_resources_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_resources") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_resources") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.SearchAllResourcesRequest.pb(asset_service.SearchAllResourcesRequest()) - 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 = asset_service.SearchAllResourcesResponse.to_json(asset_service.SearchAllResourcesResponse()) - - request = asset_service.SearchAllResourcesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.SearchAllResourcesResponse() - - client.search_all_resources(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_all_resources_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllResourcesRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.search_all_resources(request) - - -def test_search_all_resources_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.SearchAllResourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'scope': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_all_resources(**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/v1p1beta1/{scope=*/*}/resources:searchAll" % client.transport._host, args[1]) - - -def test_search_all_resources_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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.search_all_resources( - asset_service.SearchAllResourcesRequest(), - scope='scope_value', - query='query_value', - asset_types=['asset_types_value'], - ) - - -def test_search_all_resources_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - next_page_token='abc', - ), - asset_service.SearchAllResourcesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllResourcesResponse( - results=[ - assets.StandardResourceMetadata(), - assets.StandardResourceMetadata(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.SearchAllResourcesResponse.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 = {'scope': 'sample1/sample2'} - - pager = client.search_all_resources(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.StandardResourceMetadata) - for i in results) - - pages = list(client.search_all_resources(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", [ - asset_service.SearchAllIamPoliciesRequest, - dict, -]) -def test_search_all_iam_policies_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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 = asset_service.SearchAllIamPoliciesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.search_all_iam_policies(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_search_all_iam_policies_rest_required_fields(request_type=asset_service.SearchAllIamPoliciesRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["scope"] = "" - 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()).search_all_iam_policies._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["scope"] = 'scope_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).search_all_iam_policies._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", "query", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "scope" in jsonified_request - assert jsonified_request["scope"] == 'scope_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.SearchAllIamPoliciesResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.search_all_iam_policies(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_search_all_iam_policies_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.search_all_iam_policies._get_unset_required_fields({}) - assert set(unset_fields) == (set(("pageSize", "pageToken", "query", )) & set(("scope", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_all_iam_policies_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_search_all_iam_policies") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_search_all_iam_policies") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.SearchAllIamPoliciesRequest.pb(asset_service.SearchAllIamPoliciesRequest()) - 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 = asset_service.SearchAllIamPoliciesResponse.to_json(asset_service.SearchAllIamPoliciesResponse()) - - request = asset_service.SearchAllIamPoliciesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.SearchAllIamPoliciesResponse() - - client.search_all_iam_policies(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_search_all_iam_policies_rest_bad_request(transport: str = 'rest', request_type=asset_service.SearchAllIamPoliciesRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'scope': 'sample1/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.search_all_iam_policies(request) - - -def test_search_all_iam_policies_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.SearchAllIamPoliciesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'scope': 'sample1/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - scope='scope_value', - query='query_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.search_all_iam_policies(**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/v1p1beta1/{scope=*/*}/iamPolicies:searchAll" % client.transport._host, args[1]) - - -def test_search_all_iam_policies_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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.search_all_iam_policies( - asset_service.SearchAllIamPoliciesRequest(), - scope='scope_value', - query='query_value', - ) - - -def test_search_all_iam_policies_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - next_page_token='abc', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[], - next_page_token='def', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - ], - next_page_token='ghi', - ), - asset_service.SearchAllIamPoliciesResponse( - results=[ - assets.IamPolicySearchResult(), - assets.IamPolicySearchResult(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.SearchAllIamPoliciesResponse.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 = {'scope': 'sample1/sample2'} - - pager = client.search_all_iam_policies(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.IamPolicySearchResult) - for i in results) - - pages = list(client.search_all_iam_policies(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AssetServiceClient( - 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 = AssetServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AssetServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, -]) -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 = AssetServiceClient.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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AssetServiceGrpcTransport, - ) - -def test_asset_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_asset_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'search_all_resources', - 'search_all_iam_policies', - ) - 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_asset_service_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.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport( - 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_asset_service_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.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport() - adc.assert_called_once() - - -def test_asset_service_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) - AssetServiceClient() - 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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( - 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_asset_service_host_no_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_asset_service_host_with_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_asset_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AssetServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AssetServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.search_all_resources._session - session2 = client2.transport.search_all_resources._session - assert session1 != session2 - session1 = client1.transport.search_all_iam_policies._session - session2 = client2.transport.search_all_iam_policies._session - assert session1 != session2 -def test_asset_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcTransport( - 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_asset_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcAsyncIOTransport( - 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_common_billing_account_path(): - billing_account = "squid" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AssetServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AssetServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "whelk" - expected = "folders/{folder}".format(folder=folder, ) - actual = AssetServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AssetServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "oyster" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AssetServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AssetServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "cuttlefish" - expected = "projects/{project}".format(project=project, ) - actual = AssetServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AssetServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AssetServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AssetServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( - 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_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AssetServiceClient( - 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 = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), -]) -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/v1p2beta1/.coveragerc b/owl-bot-staging/v1p2beta1/.coveragerc deleted file mode 100644 index 801f6d8a..00000000 --- a/owl-bot-staging/v1p2beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py - google/cloud/asset/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/v1p2beta1/.flake8 b/owl-bot-staging/v1p2beta1/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v1p2beta1/.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/v1p2beta1/MANIFEST.in b/owl-bot-staging/v1p2beta1/MANIFEST.in deleted file mode 100644 index ff48182d..00000000 --- a/owl-bot-staging/v1p2beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/asset *.py -recursive-include google/cloud/asset_v1p2beta1 *.py diff --git a/owl-bot-staging/v1p2beta1/README.rst b/owl-bot-staging/v1p2beta1/README.rst deleted file mode 100644 index 110d4086..00000000 --- a/owl-bot-staging/v1p2beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Asset 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 Asset 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/v1p2beta1/docs/_static/custom.css b/owl-bot-staging/v1p2beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0..00000000 --- a/owl-bot-staging/v1p2beta1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst deleted file mode 100644 index 21bc405a..00000000 --- a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/asset_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -AssetService ------------------------------- - -.. automodule:: google.cloud.asset_v1p2beta1.services.asset_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst deleted file mode 100644 index f8ff126c..00000000 --- a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Asset v1p2beta1 API -============================================= -.. toctree:: - :maxdepth: 2 - - asset_service diff --git a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst deleted file mode 100644 index cfbf146e..00000000 --- a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Asset v1p2beta1 API -========================================== - -.. automodule:: google.cloud.asset_v1p2beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1p2beta1/docs/conf.py b/owl-bot-staging/v1p2beta1/docs/conf.py deleted file mode 100644 index b6b4f094..00000000 --- a/owl-bot-staging/v1p2beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-asset 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-asset" -copyright = u"2023, 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 = 'en' - -# 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-asset-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-asset.tex", - u"google-cloud-asset 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-asset", - u"Google Cloud Asset 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-asset", - u"google-cloud-asset Documentation", - author, - "google-cloud-asset", - "GAPIC library for Google Cloud Asset 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/v1p2beta1/docs/index.rst b/owl-bot-staging/v1p2beta1/docs/index.rst deleted file mode 100644 index db16927c..00000000 --- a/owl-bot-staging/v1p2beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - asset_v1p2beta1/services - asset_v1p2beta1/types diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py deleted file mode 100644 index d3707f35..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,59 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.asset_v1p2beta1.services.asset_service.client import AssetServiceClient -from google.cloud.asset_v1p2beta1.services.asset_service.async_client import AssetServiceAsyncClient - -from google.cloud.asset_v1p2beta1.types.asset_service import CreateFeedRequest -from google.cloud.asset_v1p2beta1.types.asset_service import DeleteFeedRequest -from google.cloud.asset_v1p2beta1.types.asset_service import Feed -from google.cloud.asset_v1p2beta1.types.asset_service import FeedOutputConfig -from google.cloud.asset_v1p2beta1.types.asset_service import GcsDestination -from google.cloud.asset_v1p2beta1.types.asset_service import GetFeedRequest -from google.cloud.asset_v1p2beta1.types.asset_service import ListFeedsRequest -from google.cloud.asset_v1p2beta1.types.asset_service import ListFeedsResponse -from google.cloud.asset_v1p2beta1.types.asset_service import OutputConfig -from google.cloud.asset_v1p2beta1.types.asset_service import PubsubDestination -from google.cloud.asset_v1p2beta1.types.asset_service import UpdateFeedRequest -from google.cloud.asset_v1p2beta1.types.asset_service import ContentType -from google.cloud.asset_v1p2beta1.types.assets import Asset -from google.cloud.asset_v1p2beta1.types.assets import Resource -from google.cloud.asset_v1p2beta1.types.assets import TemporalAsset -from google.cloud.asset_v1p2beta1.types.assets import TimeWindow - -__all__ = ('AssetServiceClient', - 'AssetServiceAsyncClient', - 'CreateFeedRequest', - 'DeleteFeedRequest', - 'Feed', - 'FeedOutputConfig', - 'GcsDestination', - 'GetFeedRequest', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'OutputConfig', - 'PubsubDestination', - 'UpdateFeedRequest', - 'ContentType', - 'Asset', - 'Resource', - 'TemporalAsset', - 'TimeWindow', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py deleted file mode 100644 index 257425c0..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset_v1p2beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.asset_service import AssetServiceClient -from .services.asset_service import AssetServiceAsyncClient - -from .types.asset_service import CreateFeedRequest -from .types.asset_service import DeleteFeedRequest -from .types.asset_service import Feed -from .types.asset_service import FeedOutputConfig -from .types.asset_service import GcsDestination -from .types.asset_service import GetFeedRequest -from .types.asset_service import ListFeedsRequest -from .types.asset_service import ListFeedsResponse -from .types.asset_service import OutputConfig -from .types.asset_service import PubsubDestination -from .types.asset_service import UpdateFeedRequest -from .types.asset_service import ContentType -from .types.assets import Asset -from .types.assets import Resource -from .types.assets import TemporalAsset -from .types.assets import TimeWindow - -__all__ = ( - 'AssetServiceAsyncClient', -'Asset', -'AssetServiceClient', -'ContentType', -'CreateFeedRequest', -'DeleteFeedRequest', -'Feed', -'FeedOutputConfig', -'GcsDestination', -'GetFeedRequest', -'ListFeedsRequest', -'ListFeedsResponse', -'OutputConfig', -'PubsubDestination', -'Resource', -'TemporalAsset', -'TimeWindow', -'UpdateFeedRequest', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json deleted file mode 100644 index 792efcd7..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json +++ /dev/null @@ -1,103 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.asset_v1p2beta1", - "protoPackage": "google.cloud.asset.v1p2beta1", - "schema": "1.0", - "services": { - "AssetService": { - "clients": { - "grpc": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AssetServiceAsyncClient", - "rpcs": { - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - } - } - }, - "rest": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py deleted file mode 100644 index 89a37dc9..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py deleted file mode 100644 index 542f923f..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AssetServiceClient -from .async_client import AssetServiceAsyncClient - -__all__ = ( - 'AssetServiceClient', - 'AssetServiceAsyncClient', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py deleted file mode 100644 index 3593d3e1..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,751 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.asset_v1p2beta1 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.cloud.asset_v1p2beta1.types import asset_service -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .client import AssetServiceClient - - -class AssetServiceAsyncClient: - """Asset service definition.""" - - _client: AssetServiceClient - - DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT - - feed_path = staticmethod(AssetServiceClient.feed_path) - parse_feed_path = staticmethod(AssetServiceClient.parse_feed_path) - common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AssetServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AssetServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AssetServiceClient.common_project_path) - parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) - common_location_path = staticmethod(AssetServiceClient.common_location_path) - parse_common_location_path = staticmethod(AssetServiceClient.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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_feed(self, - request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - .. 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 asset_v1p2beta1 - - async def sample_create_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = await client.create_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1p2beta1.types.CreateFeedRequest, dict]]): - The request object. Create asset feed request. - parent (:class:`str`): - Required. The name of the - project/folder/organization where this - feed should be created in. It can only - be an organization number (such as - "organizations/123"), a folder number - (such as "folders/123"), a project ID - (such as "projects/my-project-id")", or - a project number (such as - "projects/12345"). - - 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.asset_v1p2beta1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - # 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 = asset_service.CreateFeedRequest(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.create_feed, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_feed(self, - request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - .. 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 asset_v1p2beta1 - - async def sample_get_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = await client.get_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1p2beta1.types.GetFeedRequest, dict]]): - The request object. Get asset feed request. - name (:class:`str`): - Required. The name of the Feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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.asset_v1p2beta1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - # 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 = asset_service.GetFeedRequest(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_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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_feeds(self, - request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - .. 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 asset_v1p2beta1 - - async def sample_list_feeds(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_feeds(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1p2beta1.types.ListFeedsRequest, dict]]): - The request object. List asset feeds request. - parent (:class:`str`): - Required. The parent - project/folder/organization whose feeds - are to be listed. It can only be using - project/folder/organization number (such - as "folders/12345")", or a project ID - (such as "projects/my-project-id"). - - 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.asset_v1p2beta1.types.ListFeedsResponse: - - """ - # 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 = asset_service.ListFeedsRequest(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_feeds, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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_feed(self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - .. 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 asset_v1p2beta1 - - async def sample_update_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = await client.update_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1p2beta1.types.UpdateFeedRequest, dict]]): - The request object. Update asset feed request. - feed (:class:`google.cloud.asset_v1p2beta1.types.Feed`): - Required. The new values of feed details. It must match - an existing feed and the field ``name`` must be in the - format of: projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - - This corresponds to the ``feed`` 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.asset_v1p2beta1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - # 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([feed]) - 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 = asset_service.UpdateFeedRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if feed is not None: - request.feed = feed - - # 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_feed, - 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(( - ("feed.name", request.feed.name), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def delete_feed(self, - request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. - - .. 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 asset_v1p2beta1 - - async def sample_delete_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - await client.delete_feed(request=request) - - Args: - request (Optional[Union[google.cloud.asset_v1p2beta1.types.DeleteFeedRequest, dict]]): - The request object. - name (:class:`str`): - Required. The name of the feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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 = asset_service.DeleteFeedRequest(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_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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 __aenter__(self) -> "AssetServiceAsyncClient": - 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__ = ( - "AssetServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py deleted file mode 100644 index b2d6a61a..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py +++ /dev/null @@ -1,934 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.asset_v1p2beta1 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.cloud.asset_v1p2beta1.types import asset_service -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .transports.rest import AssetServiceRestTransport - - -class AssetServiceClientMeta(type): - """Metaclass for the AssetService 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[AssetServiceTransport]] - _transport_registry["grpc"] = AssetServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AssetServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AssetServiceTransport]: - """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 AssetServiceClient(metaclass=AssetServiceClientMeta): - """Asset service definition.""" - - @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 = "cloudasset.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: - AssetServiceClient: 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: - AssetServiceClient: 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) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def feed_path(project: str,feed: str,) -> str: - """Returns a fully-qualified feed string.""" - return "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) - - @staticmethod - def parse_feed_path(path: str) -> Dict[str,str]: - """Parses a feed path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/feeds/(?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, AssetServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): - # transport is a AssetServiceTransport 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_feed(self, - request: Optional[Union[asset_service.CreateFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - .. 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 asset_v1p2beta1 - - def sample_create_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = client.create_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1p2beta1.types.CreateFeedRequest, dict]): - The request object. Create asset feed request. - parent (str): - Required. The name of the - project/folder/organization where this - feed should be created in. It can only - be an organization number (such as - "organizations/123"), a folder number - (such as "folders/123"), a project ID - (such as "projects/my-project-id")", or - a project number (such as - "projects/12345"). - - 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.asset_v1p2beta1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - # 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 asset_service.CreateFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.CreateFeedRequest): - request = asset_service.CreateFeedRequest(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.create_feed] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_feed(self, - request: Optional[Union[asset_service.GetFeedRequest, 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]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - .. 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 asset_v1p2beta1 - - def sample_get_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = client.get_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1p2beta1.types.GetFeedRequest, dict]): - The request object. Get asset feed request. - name (str): - Required. The name of the Feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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.asset_v1p2beta1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - # 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 asset_service.GetFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.GetFeedRequest): - request = asset_service.GetFeedRequest(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_feed] - - # 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_feeds(self, - request: Optional[Union[asset_service.ListFeedsRequest, 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]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - .. 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 asset_v1p2beta1 - - def sample_list_feeds(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_feeds(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1p2beta1.types.ListFeedsRequest, dict]): - The request object. List asset feeds request. - parent (str): - Required. The parent - project/folder/organization whose feeds - are to be listed. It can only be using - project/folder/organization number (such - as "folders/12345")", or a project ID - (such as "projects/my-project-id"). - - 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.asset_v1p2beta1.types.ListFeedsResponse: - - """ - # 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 asset_service.ListFeedsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ListFeedsRequest): - request = asset_service.ListFeedsRequest(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_feeds] - - # 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_feed(self, - request: Optional[Union[asset_service.UpdateFeedRequest, dict]] = None, - *, - feed: Optional[asset_service.Feed] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - .. 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 asset_v1p2beta1 - - def sample_update_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = client.update_feed(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.asset_v1p2beta1.types.UpdateFeedRequest, dict]): - The request object. Update asset feed request. - feed (google.cloud.asset_v1p2beta1.types.Feed): - Required. The new values of feed details. It must match - an existing feed and the field ``name`` must be in the - format of: projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - - This corresponds to the ``feed`` 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.asset_v1p2beta1.types.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - # 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([feed]) - 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 asset_service.UpdateFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.UpdateFeedRequest): - request = asset_service.UpdateFeedRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if feed is not None: - request.feed = feed - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_feed] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("feed.name", request.feed.name), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def delete_feed(self, - request: Optional[Union[asset_service.DeleteFeedRequest, 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"""Deletes an asset feed. - - .. 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 asset_v1p2beta1 - - def sample_delete_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - client.delete_feed(request=request) - - Args: - request (Union[google.cloud.asset_v1p2beta1.types.DeleteFeedRequest, dict]): - The request object. - name (str): - Required. The name of the feed and it must be in the - format of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - - 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 asset_service.DeleteFeedRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.DeleteFeedRequest): - request = asset_service.DeleteFeedRequest(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_feed] - - # 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) -> "AssetServiceClient": - 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() - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AssetServiceClient", -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py deleted file mode 100644 index c34a5f8f..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AssetServiceTransport -from .grpc import AssetServiceGrpcTransport -from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .rest import AssetServiceRestTransport -from .rest import AssetServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AssetServiceRestTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', - 'AssetServiceRestTransport', - 'AssetServiceRestInterceptor', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py deleted file mode 100644 index 616011c6..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,226 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.asset_v1p2beta1 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.cloud.asset_v1p2beta1.types import asset_service -from google.protobuf import empty_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AssetServiceTransport(abc.ABC): - """Abstract transport class for AssetService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudasset.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_feed: gapic_v1.method.wrap_method( - self.create_feed, - default_timeout=60.0, - client_info=client_info, - ), - self.get_feed: gapic_v1.method.wrap_method( - self.get_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_feeds: gapic_v1.method.wrap_method( - self.list_feeds, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_feed: gapic_v1.method.wrap_method( - self.update_feed, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_feed: gapic_v1.method.wrap_method( - self.delete_feed, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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 create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: - raise NotImplementedError() - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: - raise NotImplementedError() - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - Union[ - asset_service.ListFeedsResponse, - Awaitable[asset_service.ListFeedsResponse] - ]]: - raise NotImplementedError() - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - Union[ - asset_service.Feed, - Awaitable[asset_service.Feed] - ]]: - raise NotImplementedError() - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - Union[ - empty_pb2.Empty, - Awaitable[empty_pb2.Empty] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AssetServiceTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py deleted file mode 100644 index cc2179d2..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,372 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.cloud.asset_v1p2beta1.types import asset_service -from google.protobuf import empty_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO - - -class AssetServiceGrpcTransport(AssetServiceTransport): - """gRPC backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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 create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - asset_service.Feed]: - r"""Return a callable for the create feed method over gRPC. - - Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Returns: - Callable[[~.CreateFeedRequest], - ~.Feed]: - 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_feed' not in self._stubs: - self._stubs['create_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/CreateFeed', - request_serializer=asset_service.CreateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['create_feed'] - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - asset_service.Feed]: - r"""Return a callable for the get feed method over gRPC. - - Gets details about an asset feed. - - Returns: - Callable[[~.GetFeedRequest], - ~.Feed]: - 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_feed' not in self._stubs: - self._stubs['get_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/GetFeed', - request_serializer=asset_service.GetFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['get_feed'] - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - asset_service.ListFeedsResponse]: - r"""Return a callable for the list feeds method over gRPC. - - Lists all asset feeds in a parent - project/folder/organization. - - Returns: - Callable[[~.ListFeedsRequest], - ~.ListFeedsResponse]: - 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_feeds' not in self._stubs: - self._stubs['list_feeds'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/ListFeeds', - request_serializer=asset_service.ListFeedsRequest.serialize, - response_deserializer=asset_service.ListFeedsResponse.deserialize, - ) - return self._stubs['list_feeds'] - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - asset_service.Feed]: - r"""Return a callable for the update feed method over gRPC. - - Updates an asset feed configuration. - - Returns: - Callable[[~.UpdateFeedRequest], - ~.Feed]: - 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_feed' not in self._stubs: - self._stubs['update_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed', - request_serializer=asset_service.UpdateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['update_feed'] - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - empty_pb2.Empty]: - r"""Return a callable for the delete feed method over gRPC. - - Deletes an asset feed. - - Returns: - Callable[[~.DeleteFeedRequest], - ~.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_feed' not in self._stubs: - self._stubs['delete_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed', - request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_feed'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AssetServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py deleted file mode 100644 index 2060aa07..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,371 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.cloud.asset_v1p2beta1.types import asset_service -from google.protobuf import empty_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AssetServiceGrpcTransport - - -class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): - """gRPC AsyncIO backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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 create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - Awaitable[asset_service.Feed]]: - r"""Return a callable for the create feed method over gRPC. - - Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Returns: - Callable[[~.CreateFeedRequest], - Awaitable[~.Feed]]: - 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_feed' not in self._stubs: - self._stubs['create_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/CreateFeed', - request_serializer=asset_service.CreateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['create_feed'] - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - Awaitable[asset_service.Feed]]: - r"""Return a callable for the get feed method over gRPC. - - Gets details about an asset feed. - - Returns: - Callable[[~.GetFeedRequest], - Awaitable[~.Feed]]: - 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_feed' not in self._stubs: - self._stubs['get_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/GetFeed', - request_serializer=asset_service.GetFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['get_feed'] - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - Awaitable[asset_service.ListFeedsResponse]]: - r"""Return a callable for the list feeds method over gRPC. - - Lists all asset feeds in a parent - project/folder/organization. - - Returns: - Callable[[~.ListFeedsRequest], - Awaitable[~.ListFeedsResponse]]: - 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_feeds' not in self._stubs: - self._stubs['list_feeds'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/ListFeeds', - request_serializer=asset_service.ListFeedsRequest.serialize, - response_deserializer=asset_service.ListFeedsResponse.deserialize, - ) - return self._stubs['list_feeds'] - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - Awaitable[asset_service.Feed]]: - r"""Return a callable for the update feed method over gRPC. - - Updates an asset feed configuration. - - Returns: - Callable[[~.UpdateFeedRequest], - Awaitable[~.Feed]]: - 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_feed' not in self._stubs: - self._stubs['update_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/UpdateFeed', - request_serializer=asset_service.UpdateFeedRequest.serialize, - response_deserializer=asset_service.Feed.deserialize, - ) - return self._stubs['update_feed'] - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - Awaitable[empty_pb2.Empty]]: - r"""Return a callable for the delete feed method over gRPC. - - Deletes an asset feed. - - Returns: - Callable[[~.DeleteFeedRequest], - 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_feed' not in self._stubs: - self._stubs['delete_feed'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed', - request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty_pb2.Empty.FromString, - ) - return self._stubs['delete_feed'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py deleted file mode 100644 index b4ad28de..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/rest.py +++ /dev/null @@ -1,747 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -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 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.asset_v1p2beta1.types import asset_service -from google.protobuf import empty_pb2 # type: ignore - -from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: - """Interceptor for AssetService. - - 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 AssetServiceRestTransport. - - .. code-block:: python - class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): - def pre_create_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_feed(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_delete_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def pre_get_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_feed(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_feeds(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_feeds(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_feed(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_feed(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) - client = AssetServiceClient(transport=transport) - - - """ - def pre_create_feed(self, request: asset_service.CreateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.CreateFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_create_feed(self, response: asset_service.Feed) -> asset_service.Feed: - """Post-rpc interceptor for create_feed - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_delete_feed(self, request: asset_service.DeleteFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.DeleteFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for delete_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def pre_get_feed(self, request: asset_service.GetFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.GetFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_get_feed(self, response: asset_service.Feed) -> asset_service.Feed: - """Post-rpc interceptor for get_feed - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_list_feeds(self, request: asset_service.ListFeedsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListFeedsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_feeds - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_list_feeds(self, response: asset_service.ListFeedsResponse) -> asset_service.ListFeedsResponse: - """Post-rpc interceptor for list_feeds - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - def pre_update_feed(self, request: asset_service.UpdateFeedRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.UpdateFeedRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_feed - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_update_feed(self, response: asset_service.Feed) -> asset_service.Feed: - """Post-rpc interceptor for update_feed - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AssetServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AssetServiceRestInterceptor - - -class AssetServiceRestTransport(AssetServiceTransport): - """REST backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateFeed(AssetServiceRestStub): - def __hash__(self): - return hash("CreateFeed") - - __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: asset_service.CreateFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.Feed: - r"""Call the create feed method over HTTP. - - Args: - request (~.asset_service.CreateFeedRequest): - The request object. Create asset feed request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1p2beta1/{parent=*/*}/feeds', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_create_feed(request, metadata) - pb_request = asset_service.CreateFeedRequest.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 = asset_service.Feed() - pb_resp = asset_service.Feed.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_feed(resp) - return resp - - class _DeleteFeed(AssetServiceRestStub): - def __hash__(self): - return hash("DeleteFeed") - - __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: asset_service.DeleteFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ): - r"""Call the delete feed method over HTTP. - - Args: - request (~.asset_service.DeleteFeedRequest): - The request object. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'delete', - 'uri': '/v1p2beta1/{name=*/*/feeds/*}', - }, - ] - request, metadata = self._interceptor.pre_delete_feed(request, metadata) - pb_request = asset_service.DeleteFeedRequest.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 _GetFeed(AssetServiceRestStub): - def __hash__(self): - return hash("GetFeed") - - __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: asset_service.GetFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.Feed: - r"""Call the get feed method over HTTP. - - Args: - request (~.asset_service.GetFeedRequest): - The request object. Get asset feed request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p2beta1/{name=*/*/feeds/*}', - }, - ] - request, metadata = self._interceptor.pre_get_feed(request, metadata) - pb_request = asset_service.GetFeedRequest.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 = asset_service.Feed() - pb_resp = asset_service.Feed.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_feed(resp) - return resp - - class _ListFeeds(AssetServiceRestStub): - def __hash__(self): - return hash("ListFeeds") - - __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: asset_service.ListFeedsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.ListFeedsResponse: - r"""Call the list feeds method over HTTP. - - Args: - request (~.asset_service.ListFeedsRequest): - The request object. List asset feeds request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.ListFeedsResponse: - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p2beta1/{parent=*/*}/feeds', - }, - ] - request, metadata = self._interceptor.pre_list_feeds(request, metadata) - pb_request = asset_service.ListFeedsRequest.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 = asset_service.ListFeedsResponse() - pb_resp = asset_service.ListFeedsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_feeds(resp) - return resp - - class _UpdateFeed(AssetServiceRestStub): - def __hash__(self): - return hash("UpdateFeed") - - __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: asset_service.UpdateFeedRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.Feed: - r"""Call the update feed method over HTTP. - - Args: - request (~.asset_service.UpdateFeedRequest): - The request object. Update asset feed request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.Feed: - An asset feed used to export asset - updates to a destinations. An asset feed - filter controls what updates are - exported. The asset feed must be created - within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1p2beta1/{feed.name=*/*/feeds/*}', - 'body': '*', - }, - ] - request, metadata = self._interceptor.pre_update_feed(request, metadata) - pb_request = asset_service.UpdateFeedRequest.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 = asset_service.Feed() - pb_resp = asset_service.Feed.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_feed(resp) - return resp - - @property - def create_feed(self) -> Callable[ - [asset_service.CreateFeedRequest], - asset_service.Feed]: - # 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._CreateFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def delete_feed(self) -> Callable[ - [asset_service.DeleteFeedRequest], - 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._DeleteFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_feed(self) -> Callable[ - [asset_service.GetFeedRequest], - asset_service.Feed]: - # 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._GetFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_feeds(self) -> Callable[ - [asset_service.ListFeedsRequest], - asset_service.ListFeedsResponse]: - # 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._ListFeeds(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_feed(self) -> Callable[ - [asset_service.UpdateFeedRequest], - asset_service.Feed]: - # 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._UpdateFeed(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AssetServiceRestTransport', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py deleted file mode 100644 index 960dd3d0..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .asset_service import ( - CreateFeedRequest, - DeleteFeedRequest, - Feed, - FeedOutputConfig, - GcsDestination, - GetFeedRequest, - ListFeedsRequest, - ListFeedsResponse, - OutputConfig, - PubsubDestination, - UpdateFeedRequest, - ContentType, -) -from .assets import ( - Asset, - Resource, - TemporalAsset, - TimeWindow, -) - -__all__ = ( - 'CreateFeedRequest', - 'DeleteFeedRequest', - 'Feed', - 'FeedOutputConfig', - 'GcsDestination', - 'GetFeedRequest', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'OutputConfig', - 'PubsubDestination', - 'UpdateFeedRequest', - 'ContentType', - 'Asset', - 'Resource', - 'TemporalAsset', - 'TimeWindow', -) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py deleted file mode 100644 index 56374f63..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py +++ /dev/null @@ -1,346 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.protobuf import field_mask_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p2beta1', - manifest={ - 'ContentType', - 'CreateFeedRequest', - 'GetFeedRequest', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'UpdateFeedRequest', - 'DeleteFeedRequest', - 'OutputConfig', - 'GcsDestination', - 'PubsubDestination', - 'FeedOutputConfig', - 'Feed', - }, -) - - -class ContentType(proto.Enum): - r"""Asset content type. - - Values: - CONTENT_TYPE_UNSPECIFIED (0): - Unspecified content type. - RESOURCE (1): - Resource metadata. - IAM_POLICY (2): - The actual IAM policy set on a resource. - """ - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - - -class CreateFeedRequest(proto.Message): - r"""Create asset feed request. - - Attributes: - parent (str): - Required. The name of the - project/folder/organization where this feed - should be created in. It can only be an - organization number (such as - "organizations/123"), a folder number (such as - "folders/123"), a project ID (such as - "projects/my-project-id")", or a project number - (such as "projects/12345"). - feed_id (str): - Required. This is the client-assigned asset - feed identifier and it needs to be unique under - a specific parent project/folder/organization. - feed (google.cloud.asset_v1p2beta1.types.Feed): - Required. The feed details. The field ``name`` must be empty - and it will be generated in the format of: - projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - feed_id: str = proto.Field( - proto.STRING, - number=2, - ) - feed: 'Feed' = proto.Field( - proto.MESSAGE, - number=3, - message='Feed', - ) - - -class GetFeedRequest(proto.Message): - r"""Get asset feed request. - - Attributes: - name (str): - Required. The name of the Feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFeedsRequest(proto.Message): - r"""List asset feeds request. - - Attributes: - parent (str): - Required. The parent - project/folder/organization whose feeds are to - be listed. It can only be using - project/folder/organization number (such as - "folders/12345")", or a project ID (such as - "projects/my-project-id"). - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFeedsResponse(proto.Message): - r""" - - Attributes: - feeds (MutableSequence[google.cloud.asset_v1p2beta1.types.Feed]): - A list of feeds. - """ - - feeds: MutableSequence['Feed'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='Feed', - ) - - -class UpdateFeedRequest(proto.Message): - r"""Update asset feed request. - - Attributes: - feed (google.cloud.asset_v1p2beta1.types.Feed): - Required. The new values of feed details. It must match an - existing feed and the field ``name`` must be in the format - of: projects/project_number/feeds/feed_id or - folders/folder_number/feeds/feed_id or - organizations/organization_number/feeds/feed_id. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Only updates the ``feed`` fields indicated by this - mask. The field mask must not be empty, and it must not - contain fields that are immutable or only set by the server. - """ - - feed: 'Feed' = proto.Field( - proto.MESSAGE, - number=1, - message='Feed', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class DeleteFeedRequest(proto.Message): - r""" - - Attributes: - name (str): - Required. The name of the feed and it must be in the format - of: projects/project_number/feeds/feed_id - folders/folder_number/feeds/feed_id - organizations/organization_number/feeds/feed_id - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class OutputConfig(proto.Message): - r"""Output configuration for export assets destination. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - gcs_destination (google.cloud.asset_v1p2beta1.types.GcsDestination): - Destination on Cloud Storage. - - This field is a member of `oneof`_ ``destination``. - """ - - gcs_destination: 'GcsDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - - -class GcsDestination(proto.Message): - r"""A Cloud Storage location. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - uri (str): - The uri of the Cloud Storage object. It's the same uri that - is used by gsutil. For example: - "gs://bucket_name/object_name". See `Viewing and Editing - Object - Metadata `__ - for more information. - - This field is a member of `oneof`_ ``object_uri``. - """ - - uri: str = proto.Field( - proto.STRING, - number=1, - oneof='object_uri', - ) - - -class PubsubDestination(proto.Message): - r"""A Cloud Pubsub destination. - - Attributes: - topic (str): - The name of the Cloud Pub/Sub topic to publish to. For - example: ``projects/PROJECT_ID/topics/TOPIC_ID``. - """ - - topic: str = proto.Field( - proto.STRING, - number=1, - ) - - -class FeedOutputConfig(proto.Message): - r"""Output configuration for asset feed destination. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - pubsub_destination (google.cloud.asset_v1p2beta1.types.PubsubDestination): - Destination on Cloud Pubsub. - - This field is a member of `oneof`_ ``destination``. - """ - - pubsub_destination: 'PubsubDestination' = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='PubsubDestination', - ) - - -class Feed(proto.Message): - r"""An asset feed used to export asset updates to a destinations. - An asset feed filter controls what updates are exported. The - asset feed must be created within a project, organization, or - folder. Supported destinations are: - - Cloud Pub/Sub topics. - - Attributes: - name (str): - Required. The format will be - projects/{project_number}/feeds/{client-assigned_feed_identifier} - or - folders/{folder_number}/feeds/{client-assigned_feed_identifier} - or - organizations/{organization_number}/feeds/{client-assigned_feed_identifier} - - The client-assigned feed identifier must be unique within - the parent project/folder/organization. - asset_names (MutableSequence[str]): - A list of the full names of the assets to receive updates. - You must specify either or both of asset_names and - asset_types. Only asset updates matching specified - asset_names and asset_types are exported to the feed. For - example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Resource - Names `__ - for more info. - asset_types (MutableSequence[str]): - A list of types of the assets to receive updates. You must - specify either or both of asset_names and asset_types. Only - asset updates matching specified asset_names and asset_types - are exported to the feed. For example: - "compute.googleapis.com/Disk" See `Introduction to Cloud - Asset - Inventory `__ - for all supported asset types. - content_type (google.cloud.asset_v1p2beta1.types.ContentType): - Asset content type. If not specified, no - content but the asset name and type will be - returned. - feed_output_config (google.cloud.asset_v1p2beta1.types.FeedOutputConfig): - Required. Feed output configuration defining - where the asset updates are published to. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - asset_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type: 'ContentType' = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - feed_output_config: 'FeedOutputConfig' = proto.Field( - proto.MESSAGE, - number=5, - message='FeedOutputConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py deleted file mode 100644 index 99d30e80..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py +++ /dev/null @@ -1,218 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.iam.v1 import policy_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p2beta1', - manifest={ - 'TemporalAsset', - 'TimeWindow', - 'Asset', - 'Resource', - }, -) - - -class TemporalAsset(proto.Message): - r"""Temporal asset. In addition to the asset, the temporal asset - includes the status of the asset and valid from and to time of - it. - - Attributes: - window (google.cloud.asset_v1p2beta1.types.TimeWindow): - The time window when the asset data and state - was observed. - deleted (bool): - If the asset is deleted or not. - asset (google.cloud.asset_v1p2beta1.types.Asset): - Asset. - """ - - window: 'TimeWindow' = proto.Field( - proto.MESSAGE, - number=1, - message='TimeWindow', - ) - deleted: bool = proto.Field( - proto.BOOL, - number=2, - ) - asset: 'Asset' = proto.Field( - proto.MESSAGE, - number=3, - message='Asset', - ) - - -class TimeWindow(proto.Message): - r"""A time window of (start_time, end_time]. - - Attributes: - start_time (google.protobuf.timestamp_pb2.Timestamp): - Start time of the time window (exclusive). - end_time (google.protobuf.timestamp_pb2.Timestamp): - End time of the time window (inclusive). - Current timestamp if not specified. - """ - - start_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class Asset(proto.Message): - r"""Cloud asset. This includes all Google Cloud Platform - resources, Cloud IAM policies, and other non-GCP assets. - - Attributes: - name (str): - The full name of the asset. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Resource - Names `__ - for more information. - asset_type (str): - Type of the asset. Example: - "compute.googleapis.com/Disk". - resource (google.cloud.asset_v1p2beta1.types.Resource): - Representation of the resource. - iam_policy (google.iam.v1.policy_pb2.Policy): - Representation of the actual Cloud IAM policy - set on a cloud resource. For each resource, - there must be at most one Cloud IAM policy set - on it. - ancestors (MutableSequence[str]): - Asset's ancestry path in Cloud Resource Manager (CRM) - hierarchy, represented as a list of relative resource names. - Ancestry path starts with the closest CRM ancestor and ends - at root. If the asset is a CRM project/folder/organization, - this starts from the asset itself. - - Example: ["projects/123456789", "folders/5432", - "organizations/1234"] - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - asset_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource: 'Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='Resource', - ) - iam_policy: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - ancestors: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=6, - ) - - -class Resource(proto.Message): - r"""Representation of a cloud resource. - - Attributes: - version (str): - The API version. Example: "v1". - discovery_document_uri (str): - The URL of the discovery document containing the resource's - JSON schema. For example: - ``"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"``. - It will be left unspecified for resources without a - discovery-based API, such as Cloud Bigtable. - discovery_name (str): - The JSON schema name listed in the discovery - document. Example: "Project". It will be left - unspecified for resources (such as Cloud - Bigtable) without a discovery-based API. - resource_url (str): - The REST URL for accessing the resource. An HTTP GET - operation using this URL returns the resource itself. - Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123``. - It will be left unspecified for resources without a REST - API. - parent (str): - The full name of the immediate parent of this resource. See - `Resource - Names `__ - for more information. - - For GCP assets, it is the parent resource defined in the - `Cloud IAM policy - hierarchy `__. - For example: - ``"//cloudresourcemanager.googleapis.com/projects/my_project_123"``. - - For third-party assets, it is up to the users to define. - data (google.protobuf.struct_pb2.Struct): - The content of the resource, in which some - sensitive fields are scrubbed away and may not - be present. - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - discovery_document_uri: str = proto.Field( - proto.STRING, - number=2, - ) - discovery_name: str = proto.Field( - proto.STRING, - number=3, - ) - resource_url: str = proto.Field( - proto.STRING, - number=4, - ) - parent: str = proto.Field( - proto.STRING, - number=5, - ) - data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p2beta1/mypy.ini b/owl-bot-staging/v1p2beta1/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/owl-bot-staging/v1p2beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1p2beta1/noxfile.py b/owl-bot-staging/v1p2beta1/noxfile.py deleted file mode 100644 index fb73a1cc..00000000 --- a/owl-bot-staging/v1p2beta1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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/asset_v1p2beta1/', - '--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==7.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/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py deleted file mode 100644 index f67a4091..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_CreateFeed_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 asset_v1p2beta1 - - -async def sample_create_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = await client.create_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_CreateFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py deleted file mode 100644 index 81a02f1e..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_CreateFeed_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 asset_v1p2beta1 - - -def sample_create_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.CreateFeedRequest( - parent="parent_value", - feed_id="feed_id_value", - feed=feed, - ) - - # Make the request - response = client.create_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_CreateFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py deleted file mode 100644 index 6cdb9735..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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 asset_v1p2beta1 - - -async def sample_delete_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - await client.delete_feed(request=request) - - -# [END cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py deleted file mode 100644 index 344ec815..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DeleteFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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 asset_v1p2beta1 - - -def sample_delete_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.DeleteFeedRequest( - name="name_value", - ) - - # Make the request - client.delete_feed(request=request) - - -# [END cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py deleted file mode 100644 index fe72e7dd..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_GetFeed_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 asset_v1p2beta1 - - -async def sample_get_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = await client.get_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_GetFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py deleted file mode 100644 index d195101d..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_GetFeed_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 asset_v1p2beta1 - - -def sample_get_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.GetFeedRequest( - name="name_value", - ) - - # Make the request - response = client.get_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_GetFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py deleted file mode 100644 index 075192eb..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListFeeds -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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 asset_v1p2beta1 - - -async def sample_list_feeds(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = await client.list_feeds(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_ListFeeds_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py deleted file mode 100644 index 75cf95b5..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListFeeds -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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 asset_v1p2beta1 - - -def sample_list_feeds(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p2beta1.ListFeedsRequest( - parent="parent_value", - ) - - # Make the request - response = client.list_feeds(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_ListFeeds_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py deleted file mode 100644 index 9dcdad41..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_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 asset_v1p2beta1 - - -async def sample_update_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = await client.update_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_async] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py b/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py deleted file mode 100644 index 697a6e4b..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateFeed -# 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-asset - - -# [START cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_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 asset_v1p2beta1 - - -def sample_update_feed(): - # Create a client - client = asset_v1p2beta1.AssetServiceClient() - - # Initialize request argument(s) - feed = asset_v1p2beta1.Feed() - feed.name = "name_value" - - request = asset_v1p2beta1.UpdateFeedRequest( - feed=feed, - ) - - # Make the request - response = client.update_feed(request=request) - - # Handle the response - print(response) - -# [END cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_sync] diff --git a/owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json b/owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json deleted file mode 100644 index 38eaede8..00000000 --- a/owl-bot-staging/v1p2beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p2beta1.json +++ /dev/null @@ -1,814 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.asset.v1p2beta1", - "version": "v1p2beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-asset", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.create_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.CreateFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "CreateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.CreateFeedRequest" - }, - { - "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.asset_v1p2beta1.types.Feed", - "shortName": "create_feed" - }, - "description": "Sample for CreateFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_CreateFeed_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1p2beta1_generated_asset_service_create_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.create_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.CreateFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "CreateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.CreateFeedRequest" - }, - { - "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.asset_v1p2beta1.types.Feed", - "shortName": "create_feed" - }, - "description": "Sample for CreateFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_CreateFeed_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1p2beta1_generated_asset_service_create_feed_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.delete_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.DeleteFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "DeleteFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.DeleteFeedRequest" - }, - { - "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_feed" - }, - "description": "Sample for DeleteFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.delete_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.DeleteFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "DeleteFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.DeleteFeedRequest" - }, - { - "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_feed" - }, - "description": "Sample for DeleteFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_DeleteFeed_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": "cloudasset_v1p2beta1_generated_asset_service_delete_feed_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.get_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.GetFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "GetFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.GetFeedRequest" - }, - { - "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.asset_v1p2beta1.types.Feed", - "shortName": "get_feed" - }, - "description": "Sample for GetFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_GetFeed_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": "cloudasset_v1p2beta1_generated_asset_service_get_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.get_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.GetFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "GetFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.GetFeedRequest" - }, - { - "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.asset_v1p2beta1.types.Feed", - "shortName": "get_feed" - }, - "description": "Sample for GetFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_GetFeed_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": "cloudasset_v1p2beta1_generated_asset_service_get_feed_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.list_feeds", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.ListFeeds", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListFeeds" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.ListFeedsRequest" - }, - { - "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.asset_v1p2beta1.types.ListFeedsResponse", - "shortName": "list_feeds" - }, - "description": "Sample for ListFeeds", - "file": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.list_feeds", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.ListFeeds", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListFeeds" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.ListFeedsRequest" - }, - { - "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.asset_v1p2beta1.types.ListFeedsResponse", - "shortName": "list_feeds" - }, - "description": "Sample for ListFeeds", - "file": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_ListFeeds_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": "cloudasset_v1p2beta1_generated_asset_service_list_feeds_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceAsyncClient.update_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.UpdateFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "UpdateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.UpdateFeedRequest" - }, - { - "name": "feed", - "type": "google.cloud.asset_v1p2beta1.types.Feed" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1p2beta1.types.Feed", - "shortName": "update_feed" - }, - "description": "Sample for UpdateFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1p2beta1_generated_asset_service_update_feed_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p2beta1.AssetServiceClient.update_feed", - "method": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService.UpdateFeed", - "service": { - "fullName": "google.cloud.asset.v1p2beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "UpdateFeed" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p2beta1.types.UpdateFeedRequest" - }, - { - "name": "feed", - "type": "google.cloud.asset_v1p2beta1.types.Feed" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.asset_v1p2beta1.types.Feed", - "shortName": "update_feed" - }, - "description": "Sample for UpdateFeed", - "file": "cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p2beta1_generated_AssetService_UpdateFeed_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudasset_v1p2beta1_generated_asset_service_update_feed_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py b/owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py deleted file mode 100644 index f6174e16..00000000 --- a/owl-bot-staging/v1p2beta1/scripts/fixup_asset_v1p2beta1_keywords.py +++ /dev/null @@ -1,180 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 assetCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_feed': ('parent', 'feed_id', 'feed', ), - 'delete_feed': ('name', ), - 'get_feed': ('name', ), - 'list_feeds': ('parent', ), - 'update_feed': ('feed', 'update_mask', ), - } - - 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=assetCallTransformer(), -): - """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 asset 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/v1p2beta1/setup.py b/owl-bot-staging/v1p2beta1/setup.py deleted file mode 100644 index 166120b0..00000000 --- a/owl-bot-staging/v1p2beta1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-asset' - - -description = "Google Cloud Asset API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/asset/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-asset" - -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/v1p2beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf99..00000000 --- a/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p2beta1/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/v1p2beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1p2beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p2beta1/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/v1p2beta1/tests/__init__.py b/owl-bot-staging/v1p2beta1/tests/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p2beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py deleted file mode 100644 index c9053953..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py +++ /dev/null @@ -1,3600 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 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.asset_v1p2beta1.services.asset_service import AssetServiceAsyncClient -from google.cloud.asset_v1p2beta1.services.asset_service import AssetServiceClient -from google.cloud.asset_v1p2beta1.services.asset_service import transports -from google.cloud.asset_v1p2beta1.types import asset_service -from google.oauth2 import service_account -from google.protobuf import field_mask_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 AssetServiceClient._get_default_mtls_endpoint(None) is None - assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceRestTransport, - ] - assert transport in available_transports - - transport = AssetServiceClient.get_transport_class("grpc") - assert transport == transports.AssetServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_asset_service_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", [ - AssetServiceClient, AssetServiceAsyncClient -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), -]) -def test_asset_service_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_asset_service_client_client_options_from_dict(): - with mock.patch('google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.CreateFeedRequest, - dict, -]) -def test_create_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - ) - response = client.create_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -def test_create_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.create_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() - -@pytest.mark.asyncio -async def test_create_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.CreateFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - )) - response = await client.create_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -@pytest.mark.asyncio -async def test_create_feed_async_from_dict(): - await test_create_feed_async(request_type=dict) - - -def test_create_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.CreateFeedRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - call.return_value = asset_service.Feed() - client.create_feed(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_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.CreateFeedRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.create_feed(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_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_feed( - 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_create_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.CreateFeedRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_create_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_feed( - 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_create_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.CreateFeedRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.GetFeedRequest, - dict, -]) -def test_get_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - ) - response = client.get_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -def test_get_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.get_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() - -@pytest.mark.asyncio -async def test_get_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.GetFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - )) - response = await client.get_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -@pytest.mark.asyncio -async def test_get_feed_async_from_dict(): - await test_get_feed_async(request_type=dict) - - -def test_get_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.GetFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - call.return_value = asset_service.Feed() - client.get_feed(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_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.GetFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.get_feed(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_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_feed( - 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_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.GetFeedRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_feed( - 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_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.GetFeedRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListFeedsRequest, - dict, -]) -def test_list_feeds(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListFeedsResponse( - ) - response = client.list_feeds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) - - -def test_list_feeds_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 = AssetServiceClient( - 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_feeds), - '__call__') as call: - client.list_feeds() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() - -@pytest.mark.asyncio -async def test_list_feeds_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListFeedsRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse( - )) - response = await client.list_feeds(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) - - -@pytest.mark.asyncio -async def test_list_feeds_async_from_dict(): - await test_list_feeds_async(request_type=dict) - - -def test_list_feeds_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListFeedsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - call.return_value = asset_service.ListFeedsResponse() - client.list_feeds(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_feeds_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListFeedsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) - await client.list_feeds(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_feeds_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListFeedsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_feeds( - 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_feeds_flattened_error(): - client = AssetServiceClient( - 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_feeds( - asset_service.ListFeedsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_feeds_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_feeds), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListFeedsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListFeedsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_feeds( - 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_feeds_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feeds( - asset_service.ListFeedsRequest(), - parent='parent_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.UpdateFeedRequest, - dict, -]) -def test_update_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - ) - response = client.update_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -def test_update_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.update_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() - -@pytest.mark.asyncio -async def test_update_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.UpdateFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - )) - response = await client.update_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -@pytest.mark.asyncio -async def test_update_feed_async_from_dict(): - await test_update_feed_async(request_type=dict) - - -def test_update_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.UpdateFeedRequest() - - request.feed.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - call.return_value = asset_service.Feed() - client.update_feed(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', - 'feed.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.UpdateFeedRequest() - - request.feed.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.update_feed(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', - 'feed.name=name_value', - ) in kw['metadata'] - - -def test_update_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_feed( - feed=asset_service.Feed(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].feed - mock_val = asset_service.Feed(name='name_value') - assert arg == mock_val - - -def test_update_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.UpdateFeedRequest(), - feed=asset_service.Feed(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_update_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.Feed() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_feed( - feed=asset_service.Feed(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].feed - mock_val = asset_service.Feed(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.UpdateFeedRequest(), - feed=asset_service.Feed(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.DeleteFeedRequest, - dict, -]) -def test_delete_feed(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_feed_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 = AssetServiceClient( - 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_feed), - '__call__') as call: - client.delete_feed() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() - -@pytest.mark.asyncio -async def test_delete_feed_async(transport: str = 'grpc_asyncio', request_type=asset_service.DeleteFeedRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_feed), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_feed(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() - - # Establish that the response is the type that we expect. - assert response is None - - -@pytest.mark.asyncio -async def test_delete_feed_async_from_dict(): - await test_delete_feed_async(request_type=dict) - - -def test_delete_feed_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.DeleteFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__call__') as call: - call.return_value = None - client.delete_feed(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_feed_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.DeleteFeedRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_feed(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_feed_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__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_feed( - 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_feed_flattened_error(): - client = AssetServiceClient( - 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_feed( - asset_service.DeleteFeedRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_delete_feed_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_feed), - '__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_feed( - 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_feed_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_feed( - asset_service.DeleteFeedRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.CreateFeedRequest, - dict, -]) -def test_create_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_feed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -def test_create_feed_rest_required_fields(request_type=asset_service.CreateFeedRequest): - transport_class = transports.AssetServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["feed_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()).create_feed._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["feedId"] = 'feed_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_feed._get_unset_required_fields(jsonified_request) - 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 "feedId" in jsonified_request - assert jsonified_request["feedId"] == 'feed_id_value' - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.Feed() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "feedId", "feed", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_create_feed") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_create_feed") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.CreateFeedRequest.pb(asset_service.CreateFeedRequest()) - 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 = asset_service.Feed.to_json(asset_service.Feed()) - - request = asset_service.CreateFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.Feed() - - client.create_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.CreateFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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.create_feed(request) - - -def test_create_feed_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.Feed() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/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 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_feed(**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/v1p2beta1/{parent=*/*}/feeds" % client.transport._host, args[1]) - - -def test_create_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.CreateFeedRequest(), - parent='parent_value', - ) - - -def test_create_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.GetFeedRequest, - dict, -]) -def test_get_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.get_feed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -def test_get_feed_rest_required_fields(request_type=asset_service.GetFeedRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feed._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_feed._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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.Feed() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.get_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_get_feed") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_get_feed") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.GetFeedRequest.pb(asset_service.GetFeedRequest()) - 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 = asset_service.Feed.to_json(asset_service.Feed()) - - request = asset_service.GetFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.Feed() - - client.get_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.GetFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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_feed(request) - - -def test_get_feed_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.Feed() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'sample1/sample2/feeds/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 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.get_feed(**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/v1p2beta1/{name=*/*/feeds/*}" % client.transport._host, args[1]) - - -def test_get_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.GetFeedRequest(), - name='name_value', - ) - - -def test_get_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListFeedsRequest, - dict, -]) -def test_list_feeds_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.ListFeedsResponse( - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_feeds(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) - - -def test_list_feeds_rest_required_fields(request_type=asset_service.ListFeedsRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feeds._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_feeds._get_unset_required_fields(jsonified_request) - 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.ListFeedsResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_feeds(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_feeds_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_feeds._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_feeds_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_feeds") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_feeds") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.ListFeedsRequest.pb(asset_service.ListFeedsRequest()) - 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 = asset_service.ListFeedsResponse.to_json(asset_service.ListFeedsResponse()) - - request = asset_service.ListFeedsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.ListFeedsResponse() - - client.list_feeds(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_feeds_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListFeedsRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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_feeds(request) - - -def test_list_feeds_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.ListFeedsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/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 - # Convert return value to protobuf type - return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_feeds(**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/v1p2beta1/{parent=*/*}/feeds" % client.transport._host, args[1]) - - -def test_list_feeds_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feeds( - asset_service.ListFeedsRequest(), - parent='parent_value', - ) - - -def test_list_feeds_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.UpdateFeedRequest, - dict, -]) -def test_update_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'feed': {'name': 'sample1/sample2/feeds/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 = asset_service.Feed( - name='name_value', - asset_names=['asset_names_value'], - asset_types=['asset_types_value'], - content_type=asset_service.ContentType.RESOURCE, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_feed(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == 'name_value' - assert response.asset_names == ['asset_names_value'] - assert response.asset_types == ['asset_types_value'] - assert response.content_type == asset_service.ContentType.RESOURCE - - -def test_update_feed_rest_required_fields(request_type=asset_service.UpdateFeedRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feed._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_feed._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.Feed() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("feed", "updateMask", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_update_feed") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_update_feed") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.UpdateFeedRequest.pb(asset_service.UpdateFeedRequest()) - 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 = asset_service.Feed.to_json(asset_service.Feed()) - - request = asset_service.UpdateFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.Feed() - - client.update_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.UpdateFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'feed': {'name': 'sample1/sample2/feeds/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.update_feed(request) - - -def test_update_feed_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.Feed() - - # get arguments that satisfy an http rule for this method - sample_request = {'feed': {'name': 'sample1/sample2/feeds/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - feed=asset_service.Feed(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_feed(**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/v1p2beta1/{feed.name=*/*/feeds/*}" % client.transport._host, args[1]) - - -def test_update_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.UpdateFeedRequest(), - feed=asset_service.Feed(name='name_value'), - ) - - -def test_update_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.DeleteFeedRequest, - dict, -]) -def test_delete_feed_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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_feed(request) - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_feed_rest_required_fields(request_type=asset_service.DeleteFeedRequest): - transport_class = transports.AssetServiceRestTransport - - 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_feed._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_feed._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 = AssetServiceClient( - 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_feed(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_delete_feed_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.delete_feed._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_feed_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "pre_delete_feed") as pre: - pre.assert_not_called() - pb_message = asset_service.DeleteFeedRequest.pb(asset_service.DeleteFeedRequest()) - 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 = asset_service.DeleteFeedRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - - client.delete_feed(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - - -def test_delete_feed_rest_bad_request(transport: str = 'rest', request_type=asset_service.DeleteFeedRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'sample1/sample2/feeds/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_feed(request) - - -def test_delete_feed_rest_flattened(): - client = AssetServiceClient( - 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': 'sample1/sample2/feeds/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_feed(**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/v1p2beta1/{name=*/*/feeds/*}" % client.transport._host, args[1]) - - -def test_delete_feed_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_feed( - asset_service.DeleteFeedRequest(), - name='name_value', - ) - - -def test_delete_feed_rest_error(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest' - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AssetServiceClient( - 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 = AssetServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AssetServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, -]) -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 = AssetServiceClient.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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AssetServiceGrpcTransport, - ) - -def test_asset_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_asset_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_feed', - 'get_feed', - 'list_feeds', - 'update_feed', - 'delete_feed', - ) - 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_asset_service_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.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport( - 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_asset_service_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.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport() - adc.assert_called_once() - - -def test_asset_service_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) - AssetServiceClient() - 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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( - 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_asset_service_host_no_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_asset_service_host_with_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_asset_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AssetServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AssetServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_feed._session - session2 = client2.transport.create_feed._session - assert session1 != session2 - session1 = client1.transport.get_feed._session - session2 = client2.transport.get_feed._session - assert session1 != session2 - session1 = client1.transport.list_feeds._session - session2 = client2.transport.list_feeds._session - assert session1 != session2 - session1 = client1.transport.update_feed._session - session2 = client2.transport.update_feed._session - assert session1 != session2 - session1 = client1.transport.delete_feed._session - session2 = client2.transport.delete_feed._session - assert session1 != session2 -def test_asset_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcTransport( - 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_asset_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcAsyncIOTransport( - 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_feed_path(): - project = "squid" - feed = "clam" - expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed, ) - actual = AssetServiceClient.feed_path(project, feed) - assert expected == actual - - -def test_parse_feed_path(): - expected = { - "project": "whelk", - "feed": "octopus", - } - path = AssetServiceClient.feed_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_feed_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AssetServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "nudibranch", - } - path = AssetServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder, ) - actual = AssetServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "mussel", - } - path = AssetServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "winkle" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AssetServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nautilus", - } - path = AssetServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "scallop" - expected = "projects/{project}".format(project=project, ) - actual = AssetServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "abalone", - } - path = AssetServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AssetServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = AssetServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( - 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_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AssetServiceClient( - 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 = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), -]) -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/v1p5beta1/.coveragerc b/owl-bot-staging/v1p5beta1/.coveragerc deleted file mode 100644 index 801f6d8a..00000000 --- a/owl-bot-staging/v1p5beta1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py - google/cloud/asset/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/v1p5beta1/.flake8 b/owl-bot-staging/v1p5beta1/.flake8 deleted file mode 100644 index 29227d4c..00000000 --- a/owl-bot-staging/v1p5beta1/.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/v1p5beta1/MANIFEST.in b/owl-bot-staging/v1p5beta1/MANIFEST.in deleted file mode 100644 index 7000a398..00000000 --- a/owl-bot-staging/v1p5beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/asset *.py -recursive-include google/cloud/asset_v1p5beta1 *.py diff --git a/owl-bot-staging/v1p5beta1/README.rst b/owl-bot-staging/v1p5beta1/README.rst deleted file mode 100644 index 110d4086..00000000 --- a/owl-bot-staging/v1p5beta1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Asset 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 Asset 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/v1p5beta1/docs/_static/custom.css b/owl-bot-staging/v1p5beta1/docs/_static/custom.css deleted file mode 100644 index 06423be0..00000000 --- a/owl-bot-staging/v1p5beta1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst deleted file mode 100644 index fa5fcb62..00000000 --- a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/asset_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -AssetService ------------------------------- - -.. automodule:: google.cloud.asset_v1p5beta1.services.asset_service - :members: - :inherited-members: - -.. automodule:: google.cloud.asset_v1p5beta1.services.asset_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst deleted file mode 100644 index 9383f20c..00000000 --- a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Asset v1p5beta1 API -============================================= -.. toctree:: - :maxdepth: 2 - - asset_service diff --git a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst deleted file mode 100644 index 0d143122..00000000 --- a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Asset v1p5beta1 API -========================================== - -.. automodule:: google.cloud.asset_v1p5beta1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/v1p5beta1/docs/conf.py b/owl-bot-staging/v1p5beta1/docs/conf.py deleted file mode 100644 index b6b4f094..00000000 --- a/owl-bot-staging/v1p5beta1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-asset 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-asset" -copyright = u"2023, 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 = 'en' - -# 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-asset-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-asset.tex", - u"google-cloud-asset 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-asset", - u"Google Cloud Asset 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-asset", - u"google-cloud-asset Documentation", - author, - "google-cloud-asset", - "GAPIC library for Google Cloud Asset 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/v1p5beta1/docs/index.rst b/owl-bot-staging/v1p5beta1/docs/index.rst deleted file mode 100644 index de7b35fd..00000000 --- a/owl-bot-staging/v1p5beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - asset_v1p5beta1/services - asset_v1p5beta1/types diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py deleted file mode 100644 index 7ecccc13..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.asset_v1p5beta1.services.asset_service.client import AssetServiceClient -from google.cloud.asset_v1p5beta1.services.asset_service.async_client import AssetServiceAsyncClient - -from google.cloud.asset_v1p5beta1.types.asset_service import ListAssetsRequest -from google.cloud.asset_v1p5beta1.types.asset_service import ListAssetsResponse -from google.cloud.asset_v1p5beta1.types.asset_service import ContentType -from google.cloud.asset_v1p5beta1.types.assets import Asset -from google.cloud.asset_v1p5beta1.types.assets import Resource - -__all__ = ('AssetServiceClient', - 'AssetServiceAsyncClient', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ContentType', - 'Asset', - 'Resource', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py b/owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py deleted file mode 100644 index 70408635..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.cloud.asset_v1p5beta1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.asset_service import AssetServiceClient -from .services.asset_service import AssetServiceAsyncClient - -from .types.asset_service import ListAssetsRequest -from .types.asset_service import ListAssetsResponse -from .types.asset_service import ContentType -from .types.assets import Asset -from .types.assets import Resource - -__all__ = ( - 'AssetServiceAsyncClient', -'Asset', -'AssetServiceClient', -'ContentType', -'ListAssetsRequest', -'ListAssetsResponse', -'Resource', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json deleted file mode 100644 index 2c3088cd..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json +++ /dev/null @@ -1,43 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.asset_v1p5beta1", - "protoPackage": "google.cloud.asset.v1p5beta1", - "schema": "1.0", - "services": { - "AssetService": { - "clients": { - "grpc": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "ListAssets": { - "methods": [ - "list_assets" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AssetServiceAsyncClient", - "rpcs": { - "ListAssets": { - "methods": [ - "list_assets" - ] - } - } - }, - "rest": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "ListAssets": { - "methods": [ - "list_assets" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py deleted file mode 100644 index 360a0d13..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py deleted file mode 100644 index 89a37dc9..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py deleted file mode 100644 index 542f923f..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AssetServiceClient -from .async_client import AssetServiceAsyncClient - -__all__ = ( - 'AssetServiceClient', - 'AssetServiceAsyncClient', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py deleted file mode 100644 index b8e79ce3..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,330 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import functools -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.asset_v1p5beta1 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.cloud.asset_v1p5beta1.services.asset_service import pagers -from google.cloud.asset_v1p5beta1.types import asset_service -from google.cloud.asset_v1p5beta1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .client import AssetServiceClient - - -class AssetServiceAsyncClient: - """Asset service definition.""" - - _client: AssetServiceClient - - DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT - - access_level_path = staticmethod(AssetServiceClient.access_level_path) - parse_access_level_path = staticmethod(AssetServiceClient.parse_access_level_path) - access_policy_path = staticmethod(AssetServiceClient.access_policy_path) - parse_access_policy_path = staticmethod(AssetServiceClient.parse_access_policy_path) - asset_path = staticmethod(AssetServiceClient.asset_path) - parse_asset_path = staticmethod(AssetServiceClient.parse_asset_path) - service_perimeter_path = staticmethod(AssetServiceClient.service_perimeter_path) - parse_service_perimeter_path = staticmethod(AssetServiceClient.parse_service_perimeter_path) - common_billing_account_path = staticmethod(AssetServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AssetServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AssetServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(AssetServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(AssetServiceClient.parse_common_organization_path) - common_project_path = staticmethod(AssetServiceClient.common_project_path) - parse_common_project_path = staticmethod(AssetServiceClient.parse_common_project_path) - common_location_path = staticmethod(AssetServiceClient.common_location_path) - parse_common_location_path = staticmethod(AssetServiceClient.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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_info.__func__(AssetServiceAsyncClient, 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: - AssetServiceAsyncClient: The constructed client. - """ - return AssetServiceClient.from_service_account_file.__func__(AssetServiceAsyncClient, 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 AssetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial(type(AssetServiceClient).get_transport_class, type(AssetServiceClient)) - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, ~.AssetServiceTransport]): 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 = AssetServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_assets(self, - request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsAsyncPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - .. 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 asset_v1p5beta1 - - async def sample_list_assets(): - # Create a client - client = asset_v1p5beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p5beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.asset_v1p5beta1.types.ListAssetsRequest, dict]]): - The request object. ListAssets request. - parent (:class:`str`): - Required. Name of the organization or project the assets - belong to. Format: "organizations/[organization-number]" - (such as "organizations/123"), "projects/[project-id]" - (such as "projects/my-project-id"), or - "projects/[project-number]" (such as "projects/12345"). - - 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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsAsyncPager: - ListAssets response. - - 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 = asset_service.ListAssetsRequest(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_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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.ListAssetsAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def __aenter__(self) -> "AssetServiceAsyncClient": - 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__ = ( - "AssetServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py deleted file mode 100644 index 7de4794f..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py +++ /dev/null @@ -1,558 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast - -from google.cloud.asset_v1p5beta1 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.cloud.asset_v1p5beta1.services.asset_service import pagers -from google.cloud.asset_v1p5beta1.types import asset_service -from google.cloud.asset_v1p5beta1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .transports.rest import AssetServiceRestTransport - - -class AssetServiceClientMeta(type): - """Metaclass for the AssetService 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[AssetServiceTransport]] - _transport_registry["grpc"] = AssetServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - _transport_registry["rest"] = AssetServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AssetServiceTransport]: - """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 AssetServiceClient(metaclass=AssetServiceClientMeta): - """Asset service definition.""" - - @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 = "cloudasset.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: - AssetServiceClient: 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: - AssetServiceClient: 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) -> AssetServiceTransport: - """Returns the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def access_level_path(access_policy: str,access_level: str,) -> str: - """Returns a fully-qualified access_level string.""" - return "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) - - @staticmethod - def parse_access_level_path(path: str) -> Dict[str,str]: - """Parses a access_level path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/accessLevels/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def access_policy_path(access_policy: str,) -> str: - """Returns a fully-qualified access_policy string.""" - return "accessPolicies/{access_policy}".format(access_policy=access_policy, ) - - @staticmethod - def parse_access_policy_path(path: str) -> Dict[str,str]: - """Parses a access_policy path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def asset_path() -> str: - """Returns a fully-qualified asset string.""" - return "*".format() - - @staticmethod - def parse_asset_path(path: str) -> Dict[str,str]: - """Parses a asset path into its component segments.""" - m = re.match(r"^.*$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_perimeter_path(access_policy: str,service_perimeter: str,) -> str: - """Returns a fully-qualified service_perimeter string.""" - return "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) - - @staticmethod - def parse_service_perimeter_path(path: str) -> Dict[str,str]: - """Parses a service_perimeter path into its component segments.""" - m = re.match(r"^accessPolicies/(?P.+?)/servicePerimeters/(?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, AssetServiceTransport]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the asset service 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, AssetServiceTransport]): 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, AssetServiceTransport): - # transport is a AssetServiceTransport 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_assets(self, - request: Optional[Union[asset_service.ListAssetsRequest, 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.ListAssetsPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - .. 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 asset_v1p5beta1 - - def sample_list_assets(): - # Create a client - client = asset_v1p5beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p5beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.asset_v1p5beta1.types.ListAssetsRequest, dict]): - The request object. ListAssets request. - parent (str): - Required. Name of the organization or project the assets - belong to. Format: "organizations/[organization-number]" - (such as "organizations/123"), "projects/[project-id]" - (such as "projects/my-project-id"), or - "projects/[project-number]" (such as "projects/12345"). - - 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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsPager: - ListAssets response. - - 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 asset_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ListAssetsRequest): - request = asset_service.ListAssetsRequest(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_assets] - - # 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.ListAssetsPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AssetServiceClient": - 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() - - - - - - - - - - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AssetServiceClient", -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py deleted file mode 100644 index 95a1ce7e..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py +++ /dev/null @@ -1,140 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator - -from google.cloud.asset_v1p5beta1.types import asset_service -from google.cloud.asset_v1p5beta1.types import assets - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``assets`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``assets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` - 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[..., asset_service.ListAssetsResponse], - request: asset_service.ListAssetsRequest, - response: asset_service.ListAssetsResponse, - *, - 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.asset_v1p5beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.asset_v1p5beta1.types.ListAssetsResponse): - 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 = asset_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[asset_service.ListAssetsResponse]: - 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[assets.Asset]: - for page in self.pages: - yield from page.assets - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``assets`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``assets`` field on the - corresponding responses. - - All the usual :class:`google.cloud.asset_v1p5beta1.types.ListAssetsResponse` - 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[asset_service.ListAssetsResponse]], - request: asset_service.ListAssetsRequest, - response: asset_service.ListAssetsResponse, - *, - 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.asset_v1p5beta1.types.ListAssetsRequest): - The initial request object. - response (google.cloud.asset_v1p5beta1.types.ListAssetsResponse): - 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 = asset_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[asset_service.ListAssetsResponse]: - 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[assets.Asset]: - async def async_generator(): - async for page in self.pages: - for response in page.assets: - 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/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py deleted file mode 100644 index c34a5f8f..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AssetServiceTransport -from .grpc import AssetServiceGrpcTransport -from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .rest import AssetServiceRestTransport -from .rest import AssetServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport -_transport_registry['rest'] = AssetServiceRestTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', - 'AssetServiceRestTransport', - 'AssetServiceRestInterceptor', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py deleted file mode 100644 index 3117d03b..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,156 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.asset_v1p5beta1 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.cloud.asset_v1p5beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AssetServiceTransport(abc.ABC): - """Abstract transport class for AssetService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - ) - - DEFAULT_HOST: str = 'cloudasset.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_assets: gapic_v1.method.wrap_method( - self.list_assets, - default_retry=retries.Retry( -initial=0.1,maximum=60.0,multiplier=1.3, predicate=retries.if_exception_type( - 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_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - Union[ - asset_service.ListAssetsResponse, - Awaitable[asset_service.ListAssetsResponse] - ]]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AssetServiceTransport', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py deleted file mode 100644 index 6f7e71a0..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,266 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.cloud.asset_v1p5beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO - - -class AssetServiceGrpcTransport(AssetServiceTransport): - """gRPC backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - asset_service.ListAssetsResponse]: - r"""Return a callable for the list assets method over gRPC. - - Lists assets with time and resource types and returns - paged results in response. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - 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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p5beta1.AssetService/ListAssets', - request_serializer=asset_service.ListAssetsRequest.serialize, - response_deserializer=asset_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - def close(self): - self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AssetServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py deleted file mode 100644 index ad3e4a30..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,265 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.cloud.asset_v1p5beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AssetServiceGrpcTransport - - -class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): - """gRPC AsyncIO backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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 = 'cloudasset.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_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - Awaitable[asset_service.ListAssetsResponse]]: - r"""Return a callable for the list assets method over gRPC. - - Lists assets with time and resource types and returns - paged results in response. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - 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_assets' not in self._stubs: - self._stubs['list_assets'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p5beta1.AssetService/ListAssets', - request_serializer=asset_service.ListAssetsRequest.serialize, - response_deserializer=asset_service.ListAssetsResponse.deserialize, - ) - return self._stubs['list_assets'] - - def close(self): - return self.grpc_channel.close() - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py deleted file mode 100644 index bd8cbb5d..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/rest.py +++ /dev/null @@ -1,289 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -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 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.asset_v1p5beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore - -from .base import AssetServiceTransport, 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 AssetServiceRestInterceptor: - """Interceptor for AssetService. - - 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 AssetServiceRestTransport. - - .. code-block:: python - class MyCustomAssetServiceInterceptor(AssetServiceRestInterceptor): - def pre_list_assets(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_assets(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AssetServiceRestTransport(interceptor=MyCustomAssetServiceInterceptor()) - client = AssetServiceClient(transport=transport) - - - """ - def pre_list_assets(self, request: asset_service.ListAssetsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[asset_service.ListAssetsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_assets - - Override in a subclass to manipulate the request or metadata - before they are sent to the AssetService server. - """ - return request, metadata - - def post_list_assets(self, response: asset_service.ListAssetsResponse) -> asset_service.ListAssetsResponse: - """Post-rpc interceptor for list_assets - - Override in a subclass to manipulate the response - after it is returned by the AssetService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AssetServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AssetServiceRestInterceptor - - -class AssetServiceRestTransport(AssetServiceTransport): - """REST backend transport for AssetService. - - Asset service definition. - - 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 = 'cloudasset.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[AssetServiceRestInterceptor] = 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 AssetServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _ListAssets(AssetServiceRestStub): - def __hash__(self): - return hash("ListAssets") - - __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: asset_service.ListAssetsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> asset_service.ListAssetsResponse: - r"""Call the list assets method over HTTP. - - Args: - request (~.asset_service.ListAssetsRequest): - The request object. ListAssets request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.ListAssetsResponse: - ListAssets response. - """ - - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1p5beta1/{parent=*/*}/assets', - }, - ] - request, metadata = self._interceptor.pre_list_assets(request, metadata) - pb_request = asset_service.ListAssetsRequest.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 = asset_service.ListAssetsResponse() - pb_resp = asset_service.ListAssetsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_assets(resp) - return resp - - @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - asset_service.ListAssetsResponse]: - # 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._ListAssets(self._session, self._host, self._interceptor) # type: ignore - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AssetServiceRestTransport', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py deleted file mode 100644 index e6aeedca..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .asset_service import ( - ListAssetsRequest, - ListAssetsResponse, - ContentType, -) -from .assets import ( - Asset, - Resource, -) - -__all__ = ( - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ContentType', - 'Asset', - 'Resource', -) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py deleted file mode 100644 index 493e4506..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py +++ /dev/null @@ -1,179 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.asset_v1p5beta1.types import assets as gca_assets -from google.protobuf import timestamp_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p5beta1', - manifest={ - 'ContentType', - 'ListAssetsRequest', - 'ListAssetsResponse', - }, -) - - -class ContentType(proto.Enum): - r"""Asset content type. - - Values: - CONTENT_TYPE_UNSPECIFIED (0): - Unspecified content type. - RESOURCE (1): - Resource metadata. - IAM_POLICY (2): - The actual IAM policy set on a resource. - ORG_POLICY (4): - The organization policy set on an asset. - ACCESS_POLICY (5): - The Access Context Manager policy set on an - asset. - """ - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - ORG_POLICY = 4 - ACCESS_POLICY = 5 - - -class ListAssetsRequest(proto.Message): - r"""ListAssets request. - - Attributes: - parent (str): - Required. Name of the organization or project the assets - belong to. Format: "organizations/[organization-number]" - (such as "organizations/123"), "projects/[project-id]" (such - as "projects/my-project-id"), or "projects/[project-number]" - (such as "projects/12345"). - read_time (google.protobuf.timestamp_pb2.Timestamp): - Timestamp to take an asset snapshot. This can - only be set to a timestamp between the current - time and the current time minus 35 days - (inclusive). If not specified, the current time - will be used. Due to delays in resource data - collection and indexing, there is a volatile - window during which running the same query may - get different results. - asset_types (MutableSequence[str]): - A list of asset types to take a snapshot for. For example: - "compute.googleapis.com/Disk". - - Regular expression is also supported. For example: - - - "compute.googleapis.com.*" snapshots resources whose - asset type starts with "compute.googleapis.com". - - ".*Instance" snapshots resources whose asset type ends - with "Instance". - - ".*Instance.*" snapshots resources whose asset type - contains "Instance". - - See `RE2 `__ for - all supported regular expression syntax. If the regular - expression does not match any supported asset type, an - INVALID_ARGUMENT error will be returned. - - If specified, only matching assets will be returned, - otherwise, it will snapshot all asset types. See - `Introduction to Cloud Asset - Inventory `__ - for all supported asset types. - content_type (google.cloud.asset_v1p5beta1.types.ContentType): - Asset content type. If not specified, no - content but the asset name will be returned. - page_size (int): - The maximum number of assets to be returned - in a single response. Default is 100, minimum is - 1, and maximum is 1000. - page_token (str): - The ``next_page_token`` returned from the previous - ``ListAssetsResponse``, or unspecified for the first - ``ListAssetsRequest``. It is a continuation of a prior - ``ListAssets`` call, and the API should return the next page - of assets. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - asset_types: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type: 'ContentType' = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - page_size: int = proto.Field( - proto.INT32, - number=5, - ) - page_token: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ListAssetsResponse(proto.Message): - r"""ListAssets response. - - Attributes: - read_time (google.protobuf.timestamp_pb2.Timestamp): - Time the snapshot was taken. - assets (MutableSequence[google.cloud.asset_v1p5beta1.types.Asset]): - Assets. - next_page_token (str): - Token to retrieve the next page of results. - It expires 72 hours after the page token for the - first page is generated. Set to empty if there - are no remaining results. - """ - - @property - def raw_page(self): - return self - - read_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - assets: MutableSequence[gca_assets.Asset] = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gca_assets.Asset, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=3, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py deleted file mode 100644 index 7ab19dd2..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py +++ /dev/null @@ -1,235 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.identity.accesscontextmanager.v1 import access_level_pb2 # type: ignore -from google.identity.accesscontextmanager.v1 import access_policy_pb2 # type: ignore -from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 # type: ignore -from google.protobuf import struct_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p5beta1', - manifest={ - 'Asset', - 'Resource', - }, -) - - -class Asset(proto.Message): - r"""An asset in Google Cloud. An asset can be any resource in the Google - Cloud `resource - hierarchy `__, - a resource outside the Google Cloud resource hierarchy (such as - Google Kubernetes Engine clusters and objects), or a policy (e.g. - IAM policy). See `Supported asset - types `__ - for more information. - - This message has `oneof`_ fields (mutually exclusive fields). - For each oneof, at most one member field can be set at the same time. - Setting any member of the oneof automatically clears all other - members. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - The full name of the asset. Example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`` - - See `Resource - names `__ - for more information. - asset_type (str): - The type of the asset. Example: - ``compute.googleapis.com/Disk`` - - See `Supported asset - types `__ - for more information. - resource (google.cloud.asset_v1p5beta1.types.Resource): - A representation of the resource. - iam_policy (google.iam.v1.policy_pb2.Policy): - A representation of the IAM policy set on a Google Cloud - resource. There can be a maximum of one IAM policy set on - any given resource. In addition, IAM policies inherit their - granted access scope from any policies set on parent - resources in the resource hierarchy. Therefore, the - effectively policy is the union of both the policy set on - this resource and each policy set on all of the resource's - ancestry resource levels in the hierarchy. See `this - topic `__ - for more information. - org_policy (MutableSequence[google.cloud.orgpolicy.v1.orgpolicy_pb2.Policy]): - A representation of an `organization - policy `__. - There can be more than one organization policy with - different constraints set on a given resource. - access_policy (google.identity.accesscontextmanager.v1.access_policy_pb2.AccessPolicy): - Please also refer to the `access policy user - guide `__. - - This field is a member of `oneof`_ ``access_context_policy``. - access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): - Please also refer to the `access level user - guide `__. - - This field is a member of `oneof`_ ``access_context_policy``. - service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): - Please also refer to the `service perimeter user - guide `__. - - This field is a member of `oneof`_ ``access_context_policy``. - ancestors (MutableSequence[str]): - The ancestry path of an asset in Google Cloud `resource - hierarchy `__, - represented as a list of relative resource names. An - ancestry path starts with the closest ancestor in the - hierarchy and ends at root. If the asset is a project, - folder, or organization, the ancestry path starts from the - asset itself. - - Example: - ``["projects/123456789", "folders/5432", "organizations/1234"]`` - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - asset_type: str = proto.Field( - proto.STRING, - number=2, - ) - resource: 'Resource' = proto.Field( - proto.MESSAGE, - number=3, - message='Resource', - ) - iam_policy: policy_pb2.Policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - org_policy: MutableSequence[orgpolicy_pb2.Policy] = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=orgpolicy_pb2.Policy, - ) - access_policy: access_policy_pb2.AccessPolicy = proto.Field( - proto.MESSAGE, - number=7, - oneof='access_context_policy', - message=access_policy_pb2.AccessPolicy, - ) - access_level: access_level_pb2.AccessLevel = proto.Field( - proto.MESSAGE, - number=8, - oneof='access_context_policy', - message=access_level_pb2.AccessLevel, - ) - service_perimeter: service_perimeter_pb2.ServicePerimeter = proto.Field( - proto.MESSAGE, - number=9, - oneof='access_context_policy', - message=service_perimeter_pb2.ServicePerimeter, - ) - ancestors: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=10, - ) - - -class Resource(proto.Message): - r"""A representation of a Google Cloud resource. - - Attributes: - version (str): - The API version. Example: "v1". - discovery_document_uri (str): - The URL of the discovery document containing the resource's - JSON schema. Example: - ``https://www.googleapis.com/discovery/v1/apis/compute/v1/rest`` - - This value is unspecified for resources that do not have an - API based on a discovery document, such as Cloud Bigtable. - discovery_name (str): - The JSON schema name listed in the discovery document. - Example: ``Project`` - - This value is unspecified for resources that do not have an - API based on a discovery document, such as Cloud Bigtable. - resource_url (str): - The REST URL for accessing the resource. An HTTP ``GET`` - request using this URL returns the resource itself. Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`` - - This value is unspecified for resources without a REST API. - parent (str): - The full name of the immediate parent of this resource. See - `Resource - Names `__ - for more information. - - For Google Cloud assets, this value is the parent resource - defined in the `IAM policy - hierarchy `__. - Example: - ``//cloudresourcemanager.googleapis.com/projects/my_project_123`` - - For third-party assets, this field may be set differently. - data (google.protobuf.struct_pb2.Struct): - The content of the resource, in which some - sensitive fields are removed and may not be - present. - """ - - version: str = proto.Field( - proto.STRING, - number=1, - ) - discovery_document_uri: str = proto.Field( - proto.STRING, - number=2, - ) - discovery_name: str = proto.Field( - proto.STRING, - number=3, - ) - resource_url: str = proto.Field( - proto.STRING, - number=4, - ) - parent: str = proto.Field( - proto.STRING, - number=5, - ) - data: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p5beta1/mypy.ini b/owl-bot-staging/v1p5beta1/mypy.ini deleted file mode 100644 index 574c5aed..00000000 --- a/owl-bot-staging/v1p5beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.7 -namespace_packages = True diff --git a/owl-bot-staging/v1p5beta1/noxfile.py b/owl-bot-staging/v1p5beta1/noxfile.py deleted file mode 100644 index f589535f..00000000 --- a/owl-bot-staging/v1p5beta1/noxfile.py +++ /dev/null @@ -1,184 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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/asset_v1p5beta1/', - '--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==7.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/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py b/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py deleted file mode 100644 index 2f32e298..00000000 --- a/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAssets -# 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-asset - - -# [START cloudasset_v1p5beta1_generated_AssetService_ListAssets_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 asset_v1p5beta1 - - -async def sample_list_assets(): - # Create a client - client = asset_v1p5beta1.AssetServiceAsyncClient() - - # Initialize request argument(s) - request = asset_v1p5beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudasset_v1p5beta1_generated_AssetService_ListAssets_async] diff --git a/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py b/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py deleted file mode 100644 index 3c5deb0a..00000000 --- a/owl-bot-staging/v1p5beta1/samples/generated_samples/cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListAssets -# 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-asset - - -# [START cloudasset_v1p5beta1_generated_AssetService_ListAssets_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 asset_v1p5beta1 - - -def sample_list_assets(): - # Create a client - client = asset_v1p5beta1.AssetServiceClient() - - # Initialize request argument(s) - request = asset_v1p5beta1.ListAssetsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_assets(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudasset_v1p5beta1_generated_AssetService_ListAssets_sync] diff --git a/owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json b/owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json deleted file mode 100644 index 13ffc229..00000000 --- a/owl-bot-staging/v1p5beta1/samples/generated_samples/snippet_metadata_google.cloud.asset.v1p5beta1.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.asset.v1p5beta1", - "version": "v1p5beta1" - } - ], - "language": "PYTHON", - "name": "google-cloud-asset", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.asset_v1p5beta1.AssetServiceAsyncClient", - "shortName": "AssetServiceAsyncClient" - }, - "fullName": "google.cloud.asset_v1p5beta1.AssetServiceAsyncClient.list_assets", - "method": { - "fullName": "google.cloud.asset.v1p5beta1.AssetService.ListAssets", - "service": { - "fullName": "google.cloud.asset.v1p5beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p5beta1.types.ListAssetsRequest" - }, - { - "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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsAsyncPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p5beta1_generated_AssetService_ListAssets_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": "cloudasset_v1p5beta1_generated_asset_service_list_assets_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.asset_v1p5beta1.AssetServiceClient", - "shortName": "AssetServiceClient" - }, - "fullName": "google.cloud.asset_v1p5beta1.AssetServiceClient.list_assets", - "method": { - "fullName": "google.cloud.asset.v1p5beta1.AssetService.ListAssets", - "service": { - "fullName": "google.cloud.asset.v1p5beta1.AssetService", - "shortName": "AssetService" - }, - "shortName": "ListAssets" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.asset_v1p5beta1.types.ListAssetsRequest" - }, - { - "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.asset_v1p5beta1.services.asset_service.pagers.ListAssetsPager", - "shortName": "list_assets" - }, - "description": "Sample for ListAssets", - "file": "cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudasset_v1p5beta1_generated_AssetService_ListAssets_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": "cloudasset_v1p5beta1_generated_asset_service_list_assets_sync.py" - } - ] -} diff --git a/owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py b/owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py deleted file mode 100644 index ec38c673..00000000 --- a/owl-bot-staging/v1p5beta1/scripts/fixup_asset_v1p5beta1_keywords.py +++ /dev/null @@ -1,176 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 assetCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), - } - - 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=assetCallTransformer(), -): - """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 asset 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/v1p5beta1/setup.py b/owl-bot-staging/v1p5beta1/setup.py deleted file mode 100644 index 166120b0..00000000 --- a/owl-bot-staging/v1p5beta1/setup.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-asset' - - -description = "Google Cloud Asset API client library" - -version = {} -with open(os.path.join(package_root, 'google/cloud/asset/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-asset" - -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/v1p5beta1/testing/constraints-3.10.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.11.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.12.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.7.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.7.txt deleted file mode 100644 index 2beecf99..00000000 --- a/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.8.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p5beta1/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/v1p5beta1/testing/constraints-3.9.txt b/owl-bot-staging/v1p5beta1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa5..00000000 --- a/owl-bot-staging/v1p5beta1/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/v1p5beta1/tests/__init__.py b/owl-bot-staging/v1p5beta1/tests/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p5beta1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/__init__.py b/owl-bot-staging/v1p5beta1/tests/unit/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py deleted file mode 100644 index 1b4db446..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py deleted file mode 100644 index 4ad268f9..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py +++ /dev/null @@ -1,1988 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2023 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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 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.asset_v1p5beta1.services.asset_service import AssetServiceAsyncClient -from google.cloud.asset_v1p5beta1.services.asset_service import AssetServiceClient -from google.cloud.asset_v1p5beta1.services.asset_service import pagers -from google.cloud.asset_v1p5beta1.services.asset_service import transports -from google.cloud.asset_v1p5beta1.types import asset_service -from google.cloud.asset_v1p5beta1.types import assets -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -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 AssetServiceClient._get_default_mtls_endpoint(None) is None - assert AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, "grpc"), - (AssetServiceAsyncClient, "grpc_asyncio"), - (AssetServiceClient, "rest"), -]) -def test_asset_service_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 == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudasset.googleapis.com' - ) - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceRestTransport, - ] - assert transport in available_transports - - transport = AssetServiceClient.get_transport_class("grpc") - assert transport == transports.AssetServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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(AssetServiceClient, '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(AssetServiceClient, '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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "true"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_asset_service_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", [ - AssetServiceClient, AssetServiceAsyncClient -]) -@mock.patch.object(AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient)) -@mock.patch.object(AssetServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceAsyncClient)) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest"), -]) -def test_asset_service_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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AssetServiceClient, transports.AssetServiceRestTransport, "rest", None), -]) -def test_asset_service_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_asset_service_client_client_options_from_dict(): - with mock.patch('google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", grpc_helpers), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListAssetsRequest, - dict, -]) -def test_list_assets(request_type, transport: str = 'grpc'): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListAssetsResponse( - next_page_token='next_page_token_value', - ) - response = client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_assets_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 = AssetServiceClient( - 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_assets), - '__call__') as call: - client.list_assets() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListAssetsRequest() - -@pytest.mark.asyncio -async def test_list_assets_async(transport: str = 'grpc_asyncio', request_type=asset_service.ListAssetsRequest): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional 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_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_assets_async_from_dict(): - await test_list_assets_async(request_type=dict) - - -def test_list_assets_field_headers(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = asset_service.ListAssetsResponse() - client.list_assets(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_assets_field_headers_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ListAssetsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) - await client.list_assets(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_assets_flattened(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListAssetsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_assets( - 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_assets_flattened_error(): - client = AssetServiceClient( - 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_assets( - asset_service.ListAssetsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_assets_flattened_async(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.ListAssetsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.ListAssetsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_assets( - 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_assets_flattened_error_async(): - client = AssetServiceAsyncClient( - 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_assets( - asset_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_pager(transport_name: str = "grpc"): - client = AssetServiceClient( - 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_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_assets(request={}) - - assert pager._metadata == metadata - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.Asset) - for i in results) -def test_list_assets_pages(transport_name: str = "grpc"): - client = AssetServiceClient( - 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_assets), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - pages = list(client.list_assets(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_assets_async_pager(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_assets(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, assets.Asset) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_assets_async_pages(): - client = AssetServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials, - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_assets), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_assets(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize("request_type", [ - asset_service.ListAssetsRequest, - dict, -]) -def test_list_assets_rest(request_type): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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 = asset_service.ListAssetsResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.list_assets(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_assets_rest_required_fields(request_type=asset_service.ListAssetsRequest): - transport_class = transports.AssetServiceRestTransport - - 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_assets._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_assets._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("asset_types", "content_type", "page_size", "page_token", "read_time", )) - 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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = asset_service.ListAssetsResponse() - # 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 - - # Convert return value to protobuf type - return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.list_assets(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_assets_rest_unset_required_fields(): - transport = transports.AssetServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_assets._get_unset_required_fields({}) - assert set(unset_fields) == (set(("assetTypes", "contentType", "pageSize", "pageToken", "readTime", )) & set(("parent", ))) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_assets_rest_interceptors(null_interceptor): - transport = transports.AssetServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AssetServiceRestInterceptor(), - ) - client = AssetServiceClient(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.AssetServiceRestInterceptor, "post_list_assets") as post, \ - mock.patch.object(transports.AssetServiceRestInterceptor, "pre_list_assets") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = asset_service.ListAssetsRequest.pb(asset_service.ListAssetsRequest()) - 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 = asset_service.ListAssetsResponse.to_json(asset_service.ListAssetsResponse()) - - request = asset_service.ListAssetsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = asset_service.ListAssetsResponse() - - client.list_assets(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_assets_rest_bad_request(transport: str = 'rest', request_type=asset_service.ListAssetsRequest): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'sample1/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_assets(request) - - -def test_list_assets_rest_flattened(): - client = AssetServiceClient( - 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 = asset_service.ListAssetsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'sample1/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 - # Convert return value to protobuf type - return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.list_assets(**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/v1p5beta1/{parent=*/*}/assets" % client.transport._host, args[1]) - - -def test_list_assets_rest_flattened_error(transport: str = 'rest'): - client = AssetServiceClient( - 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_assets( - asset_service.ListAssetsRequest(), - parent='parent_value', - ) - - -def test_list_assets_rest_pager(transport: str = 'rest'): - client = AssetServiceClient( - 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 = ( - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - assets.Asset(), - ], - next_page_token='abc', - ), - asset_service.ListAssetsResponse( - assets=[], - next_page_token='def', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - ], - next_page_token='ghi', - ), - asset_service.ListAssetsResponse( - assets=[ - assets.Asset(), - assets.Asset(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(asset_service.ListAssetsResponse.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': 'sample1/sample2'} - - pager = client.list_assets(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, assets.Asset) - for i in results) - - pages = list(client.list_assets(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AssetServiceClient( - 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 = AssetServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AssetServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, -]) -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 = AssetServiceClient.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 = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AssetServiceGrpcTransport, - ) - -def test_asset_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_asset_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AssetServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_assets', - ) - 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_asset_service_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.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport( - 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_asset_service_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.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport() - adc.assert_called_once() - - -def test_asset_service_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) - AssetServiceClient() - 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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - transports.AssetServiceRestTransport, - ], -) -def test_asset_service_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.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_asset_service_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( - "cloudasset.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="cloudasset.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_asset_service_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.AssetServiceRestTransport ( - 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_asset_service_host_no_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_asset_service_host_with_port(transport_name): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudasset.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudasset.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_asset_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AssetServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AssetServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_assets._session - session2 = client2.transport.list_assets._session - assert session1 != session2 -def test_asset_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcTransport( - 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_asset_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcAsyncIOTransport( - 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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport]) -def test_asset_service_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_access_level_path(): - access_policy = "squid" - access_level = "clam" - expected = "accessPolicies/{access_policy}/accessLevels/{access_level}".format(access_policy=access_policy, access_level=access_level, ) - actual = AssetServiceClient.access_level_path(access_policy, access_level) - assert expected == actual - - -def test_parse_access_level_path(): - expected = { - "access_policy": "whelk", - "access_level": "octopus", - } - path = AssetServiceClient.access_level_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_access_level_path(path) - assert expected == actual - -def test_access_policy_path(): - access_policy = "oyster" - expected = "accessPolicies/{access_policy}".format(access_policy=access_policy, ) - actual = AssetServiceClient.access_policy_path(access_policy) - assert expected == actual - - -def test_parse_access_policy_path(): - expected = { - "access_policy": "nudibranch", - } - path = AssetServiceClient.access_policy_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_access_policy_path(path) - assert expected == actual - -def test_asset_path(): - expected = "*".format() - actual = AssetServiceClient.asset_path() - assert expected == actual - - -def test_parse_asset_path(): - expected = { - } - path = AssetServiceClient.asset_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_asset_path(path) - assert expected == actual - -def test_service_perimeter_path(): - access_policy = "cuttlefish" - service_perimeter = "mussel" - expected = "accessPolicies/{access_policy}/servicePerimeters/{service_perimeter}".format(access_policy=access_policy, service_perimeter=service_perimeter, ) - actual = AssetServiceClient.service_perimeter_path(access_policy, service_perimeter) - assert expected == actual - - -def test_parse_service_perimeter_path(): - expected = { - "access_policy": "winkle", - "service_perimeter": "nautilus", - } - path = AssetServiceClient.service_perimeter_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_service_perimeter_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "scallop" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AssetServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "abalone", - } - path = AssetServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "squid" - expected = "folders/{folder}".format(folder=folder, ) - actual = AssetServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "clam", - } - path = AssetServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "whelk" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AssetServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "octopus", - } - path = AssetServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "oyster" - expected = "projects/{project}".format(project=project, ) - actual = AssetServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nudibranch", - } - path = AssetServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "cuttlefish" - location = "mussel" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AssetServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "winkle", - "location": "nautilus", - } - path = AssetServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.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.AssetServiceTransport, '_prep_wrapped_messages') as prep: - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AssetServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = AssetServiceClient.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 = AssetServiceAsyncClient( - 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_transport_close(): - transports = { - "rest": "_session", - "grpc": "_grpc_channel", - } - - for transport, close_name in transports.items(): - client = AssetServiceClient( - 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 = AssetServiceClient( - 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", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport), -]) -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/tests/unit/gapic/asset_v1/test_asset_service.py b/tests/unit/gapic/asset_v1/test_asset_service.py index 89d072e7..cdbb6676 100644 --- a/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1/test_asset_service.py @@ -7424,8 +7424,9 @@ def test_list_assets_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -7509,8 +7510,9 @@ def test_list_assets_rest_required_fields(request_type=asset_service.ListAssetsR response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -7647,8 +7649,9 @@ def test_list_assets_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -7764,8 +7767,9 @@ def test_batch_get_assets_history_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.BatchGetAssetsHistoryResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.BatchGetAssetsHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -7848,10 +7852,9 @@ def test_batch_get_assets_history_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.BatchGetAssetsHistoryResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.BatchGetAssetsHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8000,8 +8003,9 @@ def test_create_feed_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8083,8 +8087,9 @@ def test_create_feed_rest_required_fields(request_type=asset_service.CreateFeedR response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8216,8 +8221,9 @@ def test_create_feed_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8284,8 +8290,9 @@ def test_get_feed_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8362,8 +8369,9 @@ def test_get_feed_rest_required_fields(request_type=asset_service.GetFeedRequest response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8484,8 +8492,9 @@ def test_get_feed_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8546,8 +8555,9 @@ def test_list_feeds_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8619,8 +8629,9 @@ def test_list_feeds_rest_required_fields(request_type=asset_service.ListFeedsReq response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8743,8 +8754,9 @@ def test_list_feeds_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8811,8 +8823,9 @@ def test_update_feed_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -8885,8 +8898,9 @@ def test_update_feed_rest_required_fields(request_type=asset_service.UpdateFeedR response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -9017,8 +9031,9 @@ def test_update_feed_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -9330,8 +9345,9 @@ def test_search_all_resources_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -9417,8 +9433,9 @@ def test_search_all_resources_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -9557,8 +9574,9 @@ def test_search_all_resources_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -9680,8 +9698,9 @@ def test_search_all_iam_policies_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -9766,10 +9785,9 @@ def test_search_all_iam_policies_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllIamPoliciesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -9906,8 +9924,9 @@ def test_search_all_iam_policies_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -10028,8 +10047,9 @@ def test_analyze_iam_policy_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -10107,8 +10127,9 @@ def test_analyze_iam_policy_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeIamPolicyResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -10465,8 +10486,9 @@ def test_analyze_move_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeMoveResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeMoveResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -10554,8 +10576,9 @@ def test_analyze_move_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeMoveResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeMoveResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -10710,8 +10733,9 @@ def test_query_assets_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.QueryAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.QueryAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -10788,8 +10812,9 @@ def test_query_assets_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.QueryAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.QueryAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -10941,6 +10966,70 @@ def test_create_saved_query_rest(request_type): } }, } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = asset_service.CreateSavedQueryRequest.meta.fields["saved_query"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + else: + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + for field, value in request_init["saved_query"].items(): + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + for subfield_to_delete in subfields_not_in_runtime: + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["saved_query"][field])): + del request_init["saved_query"][field][i][subfield] + else: + del request_init["saved_query"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -10956,8 +11045,9 @@ def test_create_saved_query_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11045,8 +11135,9 @@ def test_create_saved_query_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11149,35 +11240,6 @@ def test_create_saved_query_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "sample1/sample2"} - request_init["saved_query"] = { - "name": "name_value", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "creator": "creator_value", - "last_update_time": {}, - "last_updater": "last_updater_value", - "labels": {}, - "content": { - "iam_policy_analysis_query": { - "scope": "scope_value", - "resource_selector": {"full_resource_name": "full_resource_name_value"}, - "identity_selector": {"identity": "identity_value"}, - "access_selector": { - "roles": ["roles_value1", "roles_value2"], - "permissions": ["permissions_value1", "permissions_value2"], - }, - "options": { - "expand_groups": True, - "expand_roles": True, - "expand_resources": True, - "output_resource_edges": True, - "output_group_edges": True, - "analyze_service_account_impersonation": True, - }, - "condition_context": {"access_time": {}}, - } - }, - } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -11217,8 +11279,9 @@ def test_create_saved_query_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11286,8 +11349,9 @@ def test_get_saved_query_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11365,8 +11429,9 @@ def test_get_saved_query_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11491,8 +11556,9 @@ def test_get_saved_query_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11555,8 +11621,9 @@ def test_list_saved_queries_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListSavedQueriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListSavedQueriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11639,8 +11706,9 @@ def test_list_saved_queries_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListSavedQueriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListSavedQueriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11774,8 +11842,9 @@ def test_list_saved_queries_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListSavedQueriesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListSavedQueriesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -11912,6 +11981,70 @@ def test_update_saved_query_rest(request_type): } }, } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = asset_service.UpdateSavedQueryRequest.meta.fields["saved_query"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + else: + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + for field, value in request_init["saved_query"].items(): + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + for subfield_to_delete in subfields_not_in_runtime: + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["saved_query"][field])): + del request_init["saved_query"][field][i][subfield] + else: + del request_init["saved_query"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -11927,8 +12060,9 @@ def test_update_saved_query_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -12004,8 +12138,9 @@ def test_update_saved_query_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -12101,35 +12236,6 @@ def test_update_saved_query_rest_bad_request( # send a request that will satisfy transcoding request_init = {"saved_query": {"name": "sample1/sample2/savedQueries/sample3"}} - request_init["saved_query"] = { - "name": "sample1/sample2/savedQueries/sample3", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "creator": "creator_value", - "last_update_time": {}, - "last_updater": "last_updater_value", - "labels": {}, - "content": { - "iam_policy_analysis_query": { - "scope": "scope_value", - "resource_selector": {"full_resource_name": "full_resource_name_value"}, - "identity_selector": {"identity": "identity_value"}, - "access_selector": { - "roles": ["roles_value1", "roles_value2"], - "permissions": ["permissions_value1", "permissions_value2"], - }, - "options": { - "expand_groups": True, - "expand_roles": True, - "expand_resources": True, - "output_resource_edges": True, - "output_group_edges": True, - "analyze_service_account_impersonation": True, - }, - "condition_context": {"access_time": {}}, - } - }, - } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12170,8 +12276,9 @@ def test_update_saved_query_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SavedQuery.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SavedQuery.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -12485,10 +12592,11 @@ def test_batch_get_effective_iam_policies_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb( + # Convert return value to protobuf type + return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb( return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -12571,10 +12679,11 @@ def test_batch_get_effective_iam_policies_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb( + # Convert return value to protobuf type + return_value = asset_service.BatchGetEffectiveIamPoliciesResponse.pb( return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -12728,8 +12837,9 @@ def test_analyze_org_policies_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -12820,8 +12930,9 @@ def test_analyze_org_policies_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -12969,8 +13080,9 @@ def test_analyze_org_policies_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -13095,10 +13207,11 @@ def test_analyze_org_policy_governed_containers_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb( + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb( return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -13193,12 +13306,11 @@ def test_analyze_org_policy_governed_containers_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = ( - asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb( - return_value - ) + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb( + return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -13353,10 +13465,11 @@ def test_analyze_org_policy_governed_containers_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb( + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedContainersResponse.pb( return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -13491,10 +13604,11 @@ def test_analyze_org_policy_governed_assets_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb( + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb( return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -13585,10 +13699,11 @@ def test_analyze_org_policy_governed_assets_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb( + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb( return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -13742,10 +13857,11 @@ def test_analyze_org_policy_governed_assets_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb( + # Convert return value to protobuf type + return_value = asset_service.AnalyzeOrgPolicyGovernedAssetsResponse.pb( return_value ) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value diff --git a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py index 7c039784..404c6040 100644 --- a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -1640,8 +1640,9 @@ def test_search_all_resources_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -1726,8 +1727,9 @@ def test_search_all_resources_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -1865,8 +1867,9 @@ def test_search_all_resources_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllResourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllResourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -1989,8 +1992,9 @@ def test_search_all_iam_policies_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2073,10 +2077,9 @@ def test_search_all_iam_policies_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllIamPoliciesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2211,8 +2214,9 @@ def test_search_all_iam_policies_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.SearchAllIamPoliciesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value diff --git a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py index 0eb626ae..7434e47b 100644 --- a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -1887,8 +1887,9 @@ def test_create_feed_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -1969,8 +1970,9 @@ def test_create_feed_rest_required_fields(request_type=asset_service.CreateFeedR response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2102,8 +2104,9 @@ def test_create_feed_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2169,8 +2172,9 @@ def test_get_feed_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2246,8 +2250,9 @@ def test_get_feed_rest_required_fields(request_type=asset_service.GetFeedRequest response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2368,8 +2373,9 @@ def test_get_feed_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2430,8 +2436,9 @@ def test_list_feeds_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2503,8 +2510,9 @@ def test_list_feeds_rest_required_fields(request_type=asset_service.ListFeedsReq response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2627,8 +2635,9 @@ def test_list_feeds_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListFeedsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListFeedsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2694,8 +2703,9 @@ def test_update_feed_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2767,8 +2777,9 @@ def test_update_feed_rest_required_fields(request_type=asset_service.UpdateFeedR response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -2899,8 +2910,9 @@ def test_update_feed_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.Feed.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.Feed.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value diff --git a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py index 270dd88b..81a432c4 100644 --- a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -1143,8 +1143,9 @@ def test_list_assets_rest(request_type): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -1227,8 +1228,9 @@ def test_list_assets_rest_required_fields(request_type=asset_service.ListAssetsR response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value @@ -1364,8 +1366,9 @@ def test_list_assets_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = asset_service.ListAssetsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + # Convert return value to protobuf type + return_value = asset_service.ListAssetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value