From 6cc02a2a1ff16c72914bd31986c398625192e661 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 29 Jun 2021 22:35:20 +0000 Subject: [PATCH 1/3] chore: use gapic-generator-python 0.50.3 fix: disable always_use_jwt_access Committer: @busunkim96 PiperOrigin-RevId: 382142900 Source-Link: https://github.com/googleapis/googleapis/commit/513440fda515f3c799c22a30e3906dcda325004e Source-Link: https://github.com/googleapis/googleapis-gen/commit/7b1e2c31233f79a704ec21ca410bf661d6bc68d0 --- owl-bot-staging/v1/.coveragerc | 17 + owl-bot-staging/v1/MANIFEST.in | 2 + owl-bot-staging/v1/README.rst | 49 + .../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 | 7 + owl-bot-staging/v1/docs/conf.py | 376 ++ owl-bot-staging/v1/docs/index.rst | 7 + .../v1/google/cloud/asset/__init__.py | 105 + .../v1/google/cloud/asset/py.typed | 2 + .../v1/google/cloud/asset_v1/__init__.py | 106 + .../google/cloud/asset_v1/gapic_metadata.json | 143 + .../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 | 1316 ++++++ .../asset_v1/services/asset_service/client.py | 1463 ++++++ .../asset_v1/services/asset_service/pagers.py | 385 ++ .../asset_service/transports/__init__.py | 33 + .../services/asset_service/transports/base.py | 383 ++ .../services/asset_service/transports/grpc.py | 598 +++ .../asset_service/transports/grpc_asyncio.py | 602 +++ .../google/cloud/asset_v1/types/__init__.py | 104 + .../cloud/asset_v1/types/asset_service.py | 1700 +++++++ .../v1/google/cloud/asset_v1/types/assets.py | 1084 +++++ owl-bot-staging/v1/mypy.ini | 3 + owl-bot-staging/v1/noxfile.py | 132 + .../v1/scripts/fixup_asset_v1_keywords.py | 187 + owl-bot-staging/v1/setup.py | 53 + 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 | 4046 +++++++++++++++++ owl-bot-staging/v1p1beta1/.coveragerc | 17 + owl-bot-staging/v1p1beta1/MANIFEST.in | 2 + owl-bot-staging/v1p1beta1/README.rst | 49 + .../docs/asset_v1p1beta1/asset_service.rst | 10 + .../docs/asset_v1p1beta1/services.rst | 6 + .../v1p1beta1/docs/asset_v1p1beta1/types.rst | 7 + owl-bot-staging/v1p1beta1/docs/conf.py | 376 ++ owl-bot-staging/v1p1beta1/docs/index.rst | 7 + .../v1p1beta1/google/cloud/asset/__init__.py | 37 + .../v1p1beta1/google/cloud/asset/py.typed | 2 + .../google/cloud/asset_v1p1beta1/__init__.py | 38 + .../cloud/asset_v1p1beta1/gapic_metadata.json | 43 + .../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 | 403 ++ .../services/asset_service/client.py | 567 +++ .../services/asset_service/pagers.py | 263 ++ .../asset_service/transports/__init__.py | 33 + .../services/asset_service/transports/base.py | 196 + .../services/asset_service/transports/grpc.py | 291 ++ .../asset_service/transports/grpc_asyncio.py | 295 ++ .../cloud/asset_v1p1beta1/types/__init__.py | 36 + .../asset_v1p1beta1/types/asset_service.py | 205 + .../cloud/asset_v1p1beta1/types/assets.py | 193 + owl-bot-staging/v1p1beta1/mypy.ini | 3 + owl-bot-staging/v1p1beta1/noxfile.py | 132 + .../scripts/fixup_asset_v1p1beta1_keywords.py | 177 + owl-bot-staging/v1p1beta1/setup.py | 53 + 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 | 1766 +++++++ owl-bot-staging/v1p2beta1/.coveragerc | 17 + owl-bot-staging/v1p2beta1/MANIFEST.in | 2 + owl-bot-staging/v1p2beta1/README.rst | 49 + .../docs/asset_v1p2beta1/asset_service.rst | 6 + .../docs/asset_v1p2beta1/services.rst | 6 + .../v1p2beta1/docs/asset_v1p2beta1/types.rst | 7 + owl-bot-staging/v1p2beta1/docs/conf.py | 376 ++ owl-bot-staging/v1p2beta1/docs/index.rst | 7 + .../v1p2beta1/google/cloud/asset/__init__.py | 55 + .../v1p2beta1/google/cloud/asset/py.typed | 2 + .../google/cloud/asset_v1p2beta1/__init__.py | 56 + .../cloud/asset_v1p2beta1/gapic_metadata.json | 73 + .../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 | 578 +++ .../services/asset_service/client.py | 744 +++ .../asset_service/transports/__init__.py | 33 + .../services/asset_service/transports/base.py | 246 + .../services/asset_service/transports/grpc.py | 360 ++ .../asset_service/transports/grpc_asyncio.py | 364 ++ .../cloud/asset_v1p2beta1/types/__init__.py | 54 + .../asset_v1p2beta1/types/asset_service.py | 310 ++ .../cloud/asset_v1p2beta1/types/assets.py | 212 + owl-bot-staging/v1p2beta1/mypy.ini | 3 + owl-bot-staging/v1p2beta1/noxfile.py | 132 + .../scripts/fixup_asset_v1p2beta1_keywords.py | 180 + owl-bot-staging/v1p2beta1/setup.py | 53 + 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 | 2115 +++++++++ owl-bot-staging/v1p4beta1/.coveragerc | 17 + owl-bot-staging/v1p4beta1/MANIFEST.in | 2 + owl-bot-staging/v1p4beta1/README.rst | 49 + .../docs/asset_v1p4beta1/asset_service.rst | 6 + .../docs/asset_v1p4beta1/services.rst | 6 + .../v1p4beta1/docs/asset_v1p4beta1/types.rst | 7 + owl-bot-staging/v1p4beta1/docs/conf.py | 376 ++ owl-bot-staging/v1p4beta1/docs/index.rst | 7 + .../v1p4beta1/google/cloud/asset/__init__.py | 37 + .../v1p4beta1/google/cloud/asset/py.typed | 2 + .../google/cloud/asset_v1p4beta1/__init__.py | 38 + .../cloud/asset_v1p4beta1/gapic_metadata.json | 43 + .../google/cloud/asset_v1p4beta1/py.typed | 2 + .../asset_v1p4beta1/services/__init__.py | 15 + .../services/asset_service/__init__.py | 22 + .../services/asset_service/async_client.py | 298 ++ .../services/asset_service/client.py | 472 ++ .../asset_service/transports/__init__.py | 33 + .../services/asset_service/transports/base.py | 195 + .../services/asset_service/transports/grpc.py | 304 ++ .../asset_service/transports/grpc_asyncio.py | 308 ++ .../cloud/asset_v1p4beta1/types/__init__.py | 36 + .../asset_v1p4beta1/types/asset_service.py | 534 +++ .../cloud/asset_v1p4beta1/types/assets.py | 302 ++ owl-bot-staging/v1p4beta1/mypy.ini | 3 + owl-bot-staging/v1p4beta1/noxfile.py | 132 + .../scripts/fixup_asset_v1p4beta1_keywords.py | 177 + owl-bot-staging/v1p4beta1/setup.py | 53 + owl-bot-staging/v1p4beta1/tests/__init__.py | 16 + .../v1p4beta1/tests/unit/__init__.py | 16 + .../v1p4beta1/tests/unit/gapic/__init__.py | 16 + .../unit/gapic/asset_v1p4beta1/__init__.py | 16 + .../asset_v1p4beta1/test_asset_service.py | 1254 +++++ owl-bot-staging/v1p5beta1/.coveragerc | 17 + owl-bot-staging/v1p5beta1/MANIFEST.in | 2 + owl-bot-staging/v1p5beta1/README.rst | 49 + .../docs/asset_v1p5beta1/asset_service.rst | 10 + .../docs/asset_v1p5beta1/services.rst | 6 + .../v1p5beta1/docs/asset_v1p5beta1/types.rst | 7 + owl-bot-staging/v1p5beta1/docs/conf.py | 376 ++ owl-bot-staging/v1p5beta1/docs/index.rst | 7 + .../v1p5beta1/google/cloud/asset/__init__.py | 33 + .../v1p5beta1/google/cloud/asset/py.typed | 2 + .../google/cloud/asset_v1p5beta1/__init__.py | 34 + .../cloud/asset_v1p5beta1/gapic_metadata.json | 33 + .../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 | 237 + .../services/asset_service/client.py | 418 ++ .../services/asset_service/pagers.py | 141 + .../asset_service/transports/__init__.py | 33 + .../services/asset_service/transports/base.py | 175 + .../services/asset_service/transports/grpc.py | 253 ++ .../asset_service/transports/grpc_asyncio.py | 257 ++ .../cloud/asset_v1p5beta1/types/__init__.py | 32 + .../asset_v1p5beta1/types/asset_service.py | 140 + .../cloud/asset_v1p5beta1/types/assets.py | 194 + owl-bot-staging/v1p5beta1/mypy.ini | 3 + owl-bot-staging/v1p5beta1/noxfile.py | 132 + .../scripts/fixup_asset_v1p5beta1_keywords.py | 176 + owl-bot-staging/v1p5beta1/setup.py | 53 + 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 | 1266 ++++++ 168 files changed, 33458 insertions(+) create mode 100644 owl-bot-staging/v1/.coveragerc 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/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/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/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/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/scripts/fixup_asset_v1_keywords.py create mode 100644 owl-bot-staging/v1/setup.py 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/MANIFEST.in create mode 100644 owl-bot-staging/v1p1beta1/README.rst 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/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/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/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/scripts/fixup_asset_v1p1beta1_keywords.py create mode 100644 owl-bot-staging/v1p1beta1/setup.py 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/MANIFEST.in create mode 100644 owl-bot-staging/v1p2beta1/README.rst 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/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/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/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/scripts/fixup_asset_v1p2beta1_keywords.py create mode 100644 owl-bot-staging/v1p2beta1/setup.py 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/v1p4beta1/.coveragerc create mode 100644 owl-bot-staging/v1p4beta1/MANIFEST.in create mode 100644 owl-bot-staging/v1p4beta1/README.rst create mode 100644 owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst create mode 100644 owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst create mode 100644 owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst create mode 100644 owl-bot-staging/v1p4beta1/docs/conf.py create mode 100644 owl-bot-staging/v1p4beta1/docs/index.rst create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset/py.typed create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/gapic_metadata.json create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/py.typed create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py create mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py create mode 100644 owl-bot-staging/v1p4beta1/mypy.ini create mode 100644 owl-bot-staging/v1p4beta1/noxfile.py create mode 100644 owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py create mode 100644 owl-bot-staging/v1p4beta1/setup.py create mode 100644 owl-bot-staging/v1p4beta1/tests/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/tests/unit/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py create mode 100644 owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py create mode 100644 owl-bot-staging/v1p5beta1/.coveragerc 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/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/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/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/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/scripts/fixup_asset_v1p5beta1_keywords.py create mode 100644 owl-bot-staging/v1p5beta1/setup.py 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..3425850c --- /dev/null +++ b/owl-bot-staging/v1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound 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/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..c75a1efd --- /dev/null +++ b/owl-bot-staging/v1/docs/asset_v1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Asset v1 API +=================================== + +.. automodule:: google.cloud.asset_v1.types + :members: + :undoc-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..3aa26721 --- /dev/null +++ b/owl-bot-staging/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-asset" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-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 = [ + ( + master_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 = [ + ( + master_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 = [ + ( + master_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..815c196c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset/__init__.py @@ -0,0 +1,105 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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 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 BatchGetAssetsHistoryRequest +from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryResponse +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 DeleteFeedRequest +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 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 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 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 UpdateFeedRequest +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 ConditionEvaluation +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 Resource +from google.cloud.asset_v1.types.assets import ResourceSearchResult +from google.cloud.asset_v1.types.assets import TemporalAsset +from google.cloud.asset_v1.types.assets import TimeWindow + +__all__ = ('AssetServiceClient', + 'AssetServiceAsyncClient', + 'AnalyzeIamPolicyLongrunningRequest', + 'AnalyzeIamPolicyLongrunningResponse', + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'BatchGetAssetsHistoryRequest', + 'BatchGetAssetsHistoryResponse', + 'BigQueryDestination', + 'CreateFeedRequest', + 'DeleteFeedRequest', + 'ExportAssetsRequest', + 'ExportAssetsResponse', + 'Feed', + 'FeedOutputConfig', + 'GcsDestination', + 'GcsOutputResult', + 'GetFeedRequest', + 'IamPolicyAnalysisOutputConfig', + 'IamPolicyAnalysisQuery', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'OutputConfig', + 'OutputResult', + 'PartitionSpec', + 'PubsubDestination', + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'UpdateFeedRequest', + 'ContentType', + 'Asset', + 'ConditionEvaluation', + 'IamPolicyAnalysisResult', + 'IamPolicyAnalysisState', + 'IamPolicySearchResult', + 'Resource', + 'ResourceSearchResult', + 'TemporalAsset', + 'TimeWindow', +) 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..35fdc066 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py @@ -0,0 +1,106 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + +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 BatchGetAssetsHistoryRequest +from .types.asset_service import BatchGetAssetsHistoryResponse +from .types.asset_service import BigQueryDestination +from .types.asset_service import CreateFeedRequest +from .types.asset_service import DeleteFeedRequest +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 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 OutputConfig +from .types.asset_service import OutputResult +from .types.asset_service import PartitionSpec +from .types.asset_service import PubsubDestination +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 UpdateFeedRequest +from .types.asset_service import ContentType +from .types.assets import Asset +from .types.assets import ConditionEvaluation +from .types.assets import IamPolicyAnalysisResult +from .types.assets import IamPolicyAnalysisState +from .types.assets import IamPolicySearchResult +from .types.assets import Resource +from .types.assets import ResourceSearchResult +from .types.assets import TemporalAsset +from .types.assets import TimeWindow + +__all__ = ( + 'AssetServiceAsyncClient', +'AnalyzeIamPolicyLongrunningRequest', +'AnalyzeIamPolicyLongrunningResponse', +'AnalyzeIamPolicyRequest', +'AnalyzeIamPolicyResponse', +'Asset', +'AssetServiceClient', +'BatchGetAssetsHistoryRequest', +'BatchGetAssetsHistoryResponse', +'BigQueryDestination', +'ConditionEvaluation', +'ContentType', +'CreateFeedRequest', +'DeleteFeedRequest', +'ExportAssetsRequest', +'ExportAssetsResponse', +'Feed', +'FeedOutputConfig', +'GcsDestination', +'GcsOutputResult', +'GetFeedRequest', +'IamPolicyAnalysisOutputConfig', +'IamPolicyAnalysisQuery', +'IamPolicyAnalysisResult', +'IamPolicyAnalysisState', +'IamPolicySearchResult', +'ListAssetsRequest', +'ListAssetsResponse', +'ListFeedsRequest', +'ListFeedsResponse', +'OutputConfig', +'OutputResult', +'PartitionSpec', +'PubsubDestination', +'Resource', +'ResourceSearchResult', +'SearchAllIamPoliciesRequest', +'SearchAllIamPoliciesResponse', +'SearchAllResourcesRequest', +'SearchAllResourcesResponse', +'TemporalAsset', +'TimeWindow', +'UpdateFeedRequest', +) 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..eebf25a1 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json @@ -0,0 +1,143 @@ + { + "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" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "batch_get_assets_history" + ] + }, + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "ExportAssets": { + "methods": [ + "export_assets" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "AnalyzeIamPolicyLongrunning": { + "methods": [ + "analyze_iam_policy_longrunning" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "batch_get_assets_history" + ] + }, + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "ExportAssets": { + "methods": [ + "export_assets" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListAssets": { + "methods": [ + "list_assets" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + } + } + } + } +} 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..4de65971 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..357f9520 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..ab3d0f1b --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py @@ -0,0 +1,1316 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # 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.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 + + 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) + 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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: 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: asset_service.ExportAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 proto 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. + + Args: + request (:class:`google.cloud.asset_v1.types.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: + 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: asset_service.ListAssetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + Args: + request (:class:`google.cloud.asset_v1.types.ListAssetsRequest`): + 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_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. + # Sanity 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: asset_service.BatchGetAssetsHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.asset_v1.types.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: + 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: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (:class:`google.cloud.asset_v1.types.CreateFeedRequest`): + 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. + # Sanity 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: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (:class:`google.cloud.asset_v1.types.GetFeedRequest`): + 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. + # Sanity 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: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (:class:`google.cloud.asset_v1.types.ListFeedsRequest`): + 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. + # Sanity 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: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (:class:`google.cloud.asset_v1.types.UpdateFeedRequest`): + 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. + # Sanity 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: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (:class:`google.cloud.asset_v1.types.DeleteFeedRequest`): + 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. + # Sanity 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: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesAsyncPager: + r"""Searches all 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. + + Args: + request (:class:`google.cloud.asset_v1.types.SearchAllResourcesRequest`): + 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 Cloud resources whose name + contains "Important" as a word. + - ``name=Important`` to find the Cloud resource whose + name is exactly "Important". + - ``displayName:Impor*`` to find Cloud resources whose + display name contains "Impor" as a prefix of any word + in the field. + - ``location:us-west*`` to find Cloud resources whose + location contains both "us" and "west" as prefixes. + - ``labels:prod`` to find Cloud resources whose labels + contain "prod" as a key or value. + - ``labels.env:prod`` to find Cloud resources that have + a label "env" and its value is "prod". + - ``labels.env:*`` to find Cloud resources that have a + label "env". + - ``kmsKey:key`` to find Cloud resources encrypted with + a customer-managed encryption key whose name contains + the word "key". + - ``state:ACTIVE`` to find Cloud resources whose state + contains "ACTIVE" as a word. + - ``NOT state:ACTIVE`` to find {{gcp_name}} resources + whose state doesn't contain "ACTIVE" as a word. + - ``createTime<1609459200`` to find 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 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 Cloud resources that contain + "Important" as a word in any of the searchable + fields. + - ``Impor*`` to find 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 + 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:`Sequence[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. + # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (:class:`google.cloud.asset_v1.types.SearchAllIamPoliciesRequest`): + 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 Cloud IAM policy binding, including its + members, roles, and Cloud IAM conditions. The returned + Cloud IAM policies will only contain the bindings that + match your query. To learn more about the IAM policy + structure, see `IAM policy + doc `__. + + 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 "user" member type. + + 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. + # Sanity 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: asset_service.AnalyzeIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies to answer which identities have + what accesses on which resources. + + Args: + request (:class:`google.cloud.asset_v1.types.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: + 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: asset_service.AnalyzeIamPolicyLongrunningRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 request + to help callers to map responses to requests. + + Args: + request (:class:`google.cloud.asset_v1.types.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: + 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.AnalyzeIamPolicyLongrunningRequest, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..aa285d83 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py @@ -0,0 +1,1463 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +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.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 + + +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 + + def get_transport_class(cls, + label: 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 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport, None] = None, + client_options: Optional[client_options_lib.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 (google.api_core.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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: + 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: + 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, + ) + + def export_assets(self, + request: asset_service.ExportAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 proto 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. + + Args: + request (google.cloud.asset_v1.types.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: + 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: asset_service.ListAssetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + Args: + request (google.cloud.asset_v1.types.ListAssetsRequest): + 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_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. + # Sanity 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: asset_service.BatchGetAssetsHistoryRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.asset_v1.types.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: + 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: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (google.cloud.asset_v1.types.CreateFeedRequest): + 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. + # Sanity 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: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (google.cloud.asset_v1.types.GetFeedRequest): + 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. + # Sanity 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: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (google.cloud.asset_v1.types.ListFeedsRequest): + 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. + # Sanity 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: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (google.cloud.asset_v1.types.UpdateFeedRequest): + 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. + # Sanity 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: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (google.cloud.asset_v1.types.DeleteFeedRequest): + 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. + # Sanity 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: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesPager: + r"""Searches all 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. + + Args: + request (google.cloud.asset_v1.types.SearchAllResourcesRequest): + 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 Cloud resources whose name + contains "Important" as a word. + - ``name=Important`` to find the Cloud resource whose + name is exactly "Important". + - ``displayName:Impor*`` to find Cloud resources whose + display name contains "Impor" as a prefix of any word + in the field. + - ``location:us-west*`` to find Cloud resources whose + location contains both "us" and "west" as prefixes. + - ``labels:prod`` to find Cloud resources whose labels + contain "prod" as a key or value. + - ``labels.env:prod`` to find Cloud resources that have + a label "env" and its value is "prod". + - ``labels.env:*`` to find Cloud resources that have a + label "env". + - ``kmsKey:key`` to find Cloud resources encrypted with + a customer-managed encryption key whose name contains + the word "key". + - ``state:ACTIVE`` to find Cloud resources whose state + contains "ACTIVE" as a word. + - ``NOT state:ACTIVE`` to find {{gcp_name}} resources + whose state doesn't contain "ACTIVE" as a word. + - ``createTime<1609459200`` to find 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 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 Cloud resources that contain + "Important" as a word in any of the searchable + fields. + - ``Impor*`` to find 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 + 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 (Sequence[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. + # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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. + + Args: + request (google.cloud.asset_v1.types.SearchAllIamPoliciesRequest): + 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 Cloud IAM policy binding, including its + members, roles, and Cloud IAM conditions. The returned + Cloud IAM policies will only contain the bindings that + match your query. To learn more about the IAM policy + structure, see `IAM policy + doc `__. + + 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 "user" member type. + + 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. + # Sanity 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: asset_service.AnalyzeIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies to answer which identities have + what accesses on which resources. + + Args: + request (google.cloud.asset_v1.types.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: + 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: asset_service.AnalyzeIamPolicyLongrunningRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + 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 request + to help callers to map responses to requests. + + Args: + request (google.cloud.asset_v1.types.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: + 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.AnalyzeIamPolicyLongrunningRequest, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..c09af15c --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py @@ -0,0 +1,385 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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/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..2c12069f --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', +) 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..f2ec182e --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -0,0 +1,383 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-asset', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +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: 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, + **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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, 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) + + # If the credentials is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + 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, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """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() + + +__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..d20c2b24 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -0,0 +1,598 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> 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 applicatin 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 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 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 = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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: ga_credentials.Credentials = None, + credentials_file: 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. + """ + # Sanity 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 proto 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 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 request + to help callers to map responses to requests. + + 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'] + + +__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..0634b4f4 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,602 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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 applicatin 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 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 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 = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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. + """ + # Sanity 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 proto 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 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 request + to help callers to map responses to requests. + + 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'] + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) 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..f20e2224 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py @@ -0,0 +1,104 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ( + AnalyzeIamPolicyLongrunningRequest, + AnalyzeIamPolicyLongrunningResponse, + AnalyzeIamPolicyRequest, + AnalyzeIamPolicyResponse, + BatchGetAssetsHistoryRequest, + BatchGetAssetsHistoryResponse, + BigQueryDestination, + CreateFeedRequest, + DeleteFeedRequest, + ExportAssetsRequest, + ExportAssetsResponse, + Feed, + FeedOutputConfig, + GcsDestination, + GcsOutputResult, + GetFeedRequest, + IamPolicyAnalysisOutputConfig, + IamPolicyAnalysisQuery, + ListAssetsRequest, + ListAssetsResponse, + ListFeedsRequest, + ListFeedsResponse, + OutputConfig, + OutputResult, + PartitionSpec, + PubsubDestination, + SearchAllIamPoliciesRequest, + SearchAllIamPoliciesResponse, + SearchAllResourcesRequest, + SearchAllResourcesResponse, + UpdateFeedRequest, + ContentType, +) +from .assets import ( + Asset, + ConditionEvaluation, + IamPolicyAnalysisResult, + IamPolicyAnalysisState, + IamPolicySearchResult, + Resource, + ResourceSearchResult, + TemporalAsset, + TimeWindow, +) + +__all__ = ( + 'AnalyzeIamPolicyLongrunningRequest', + 'AnalyzeIamPolicyLongrunningResponse', + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'BatchGetAssetsHistoryRequest', + 'BatchGetAssetsHistoryResponse', + 'BigQueryDestination', + 'CreateFeedRequest', + 'DeleteFeedRequest', + 'ExportAssetsRequest', + 'ExportAssetsResponse', + 'Feed', + 'FeedOutputConfig', + 'GcsDestination', + 'GcsOutputResult', + 'GetFeedRequest', + 'IamPolicyAnalysisOutputConfig', + 'IamPolicyAnalysisQuery', + 'ListAssetsRequest', + 'ListAssetsResponse', + 'ListFeedsRequest', + 'ListFeedsResponse', + 'OutputConfig', + 'OutputResult', + 'PartitionSpec', + 'PubsubDestination', + 'SearchAllIamPoliciesRequest', + 'SearchAllIamPoliciesResponse', + 'SearchAllResourcesRequest', + 'SearchAllResourcesResponse', + 'UpdateFeedRequest', + 'ContentType', + 'Asset', + 'ConditionEvaluation', + 'IamPolicyAnalysisResult', + 'IamPolicyAnalysisState', + 'IamPolicySearchResult', + 'Resource', + 'ResourceSearchResult', + 'TemporalAsset', + 'TimeWindow', +) 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..8ecee480 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py @@ -0,0 +1,1700 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.asset_v1.types import assets as gca_assets +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.type import expr_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1', + manifest={ + 'ContentType', + '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', + }, +) + + +class ContentType(proto.Enum): + r"""Asset content type.""" + CONTENT_TYPE_UNSPECIFIED = 0 + RESOURCE = 1 + IAM_POLICY = 2 + ORG_POLICY = 4 + ACCESS_POLICY = 5 + OS_INVENTORY = 6 + + +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 (Sequence[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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + output_config = proto.Field( + proto.MESSAGE, + number=5, + message='OutputConfig', + ) + + +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 Google 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 Google Cloud Storage object limit. + """ + + read_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + output_config = proto.Field( + proto.MESSAGE, + number=2, + message='OutputConfig', + ) + output_result = proto.Field( + proto.MESSAGE, + number=3, + message='OutputResult', + ) + + +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 (Sequence[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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + page_size = proto.Field( + proto.INT32, + number=5, + ) + page_token = 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 (Sequence[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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + assets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gca_assets.Asset, + ) + next_page_token = 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 (Sequence[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. + """ + + parent = proto.Field( + proto.STRING, + number=1, + ) + asset_names = proto.RepeatedField( + proto.STRING, + number=2, + ) + content_type = proto.Field( + proto.ENUM, + number=3, + enum='ContentType', + ) + read_time_window = proto.Field( + proto.MESSAGE, + number=4, + message=gca_assets.TimeWindow, + ) + + +class BatchGetAssetsHistoryResponse(proto.Message): + r"""Batch get assets history response. + Attributes: + assets (Sequence[google.cloud.asset_v1.types.TemporalAsset]): + A list of assets with valid time windows. + """ + + assets = 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 = proto.Field( + proto.STRING, + number=1, + ) + feed_id = proto.Field( + proto.STRING, + number=2, + ) + 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFeedsResponse(proto.Message): + r""" + Attributes: + feeds (Sequence[google.cloud.asset_v1.types.Feed]): + A list of feeds. + """ + + feeds = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Feed', + ) + update_mask = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class OutputConfig(proto.Message): + r"""Output configuration for export assets destination. + Attributes: + gcs_destination (google.cloud.asset_v1.types.GcsDestination): + Destination on Cloud Storage. + bigquery_destination (google.cloud.asset_v1.types.BigQueryDestination): + Destination on BigQuery. The output table + stores the fields in asset proto as columns in + BigQuery. + """ + + gcs_destination = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + bigquery_destination = proto.Field( + proto.MESSAGE, + number=2, + oneof='destination', + message='BigQueryDestination', + ) + + +class OutputResult(proto.Message): + r"""Output result of export assets. + Attributes: + gcs_result (google.cloud.asset_v1.types.GcsOutputResult): + Export result on Cloud Storage. + """ + + gcs_result = proto.Field( + proto.MESSAGE, + number=1, + oneof='result', + message='GcsOutputResult', + ) + + +class GcsOutputResult(proto.Message): + r"""A Cloud Storage output result. + Attributes: + uris (Sequence[str]): + List of uris of the Cloud Storage objects. Example: + "gs://bucket_name/object_name". + """ + + uris = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class GcsDestination(proto.Message): + r"""A Cloud Storage location. + 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. + 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. + """ + + uri = proto.Field( + proto.STRING, + number=1, + oneof='object_uri', + ) + uri_prefix = 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. + 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 = proto.Field( + proto.STRING, + number=1, + ) + table = proto.Field( + proto.STRING, + number=2, + ) + force = proto.Field( + proto.BOOL, + number=3, + ) + partition_spec = proto.Field( + proto.MESSAGE, + number=4, + message='PartitionSpec', + ) + separate_tables_per_asset_type = 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). + """ + PARTITION_KEY_UNSPECIFIED = 0 + READ_TIME = 1 + REQUEST_TIME = 2 + + partition_key = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class FeedOutputConfig(proto.Message): + r"""Output configuration for asset feed destination. + Attributes: + pubsub_destination (google.cloud.asset_v1.types.PubsubDestination): + Destination on Pub/Sub. + """ + + pubsub_destination = 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 (Sequence[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``. + See `Resource + Names `__ + for more info. + asset_types (Sequence[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"`` + + See `this + topic `__ + for a list of all 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. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + asset_names = proto.RepeatedField( + proto.STRING, + number=2, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + feed_output_config = proto.Field( + proto.MESSAGE, + number=5, + message='FeedOutputConfig', + ) + condition = proto.Field( + proto.MESSAGE, + number=6, + message=expr_pb2.Expr, + ) + + +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 Cloud resources whose name + contains "Important" as a word. + - ``name=Important`` to find the Cloud resource whose name + is exactly "Important". + - ``displayName:Impor*`` to find Cloud resources whose + display name contains "Impor" as a prefix of any word in + the field. + - ``location:us-west*`` to find Cloud resources whose + location contains both "us" and "west" as prefixes. + - ``labels:prod`` to find Cloud resources whose labels + contain "prod" as a key or value. + - ``labels.env:prod`` to find Cloud resources that have a + label "env" and its value is "prod". + - ``labels.env:*`` to find Cloud resources that have a + label "env". + - ``kmsKey:key`` to find Cloud resources encrypted with a + customer-managed encryption key whose name contains the + word "key". + - ``state:ACTIVE`` to find Cloud resources whose state + contains "ACTIVE" as a word. + - ``NOT state:ACTIVE`` to find {{gcp_name}} resources whose + state doesn't contain "ACTIVE" as a word. + - ``createTime<1609459200`` to find 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 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 Cloud resources that contain + "Important" as a word in any of the searchable fields. + - ``Impor*`` to find 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 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 (Sequence[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, 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 singular primitive + fields in the response are sortable: + + - name + - assetType + - project + - displayName + - description + - location + - kmsKey + - createTime + - updateTime + - state + - parentFullResourceName + - parentAssetType All the other fields such as repeated + fields (e.g., ``networkTags``), map fields (e.g., + ``labels``) and struct fields (e.g., + ``additionalAttributes``) are not supported. + """ + + scope = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + page_token = proto.Field( + proto.STRING, + number=5, + ) + order_by = proto.Field( + proto.STRING, + number=6, + ) + + +class SearchAllResourcesResponse(proto.Message): + r"""Search all resources response. + Attributes: + results (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gca_assets.ResourceSearchResult, + ) + next_page_token = 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 Cloud + IAM policy binding, including its members, roles, and Cloud + IAM conditions. The returned Cloud IAM policies will only + contain the bindings that match your query. To learn more + about the IAM policy structure, see `IAM policy + doc `__. + + 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 "user" member type. + 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. + asset_types (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=5, + ) + order_by = proto.Field( + proto.STRING, + number=7, + ) + + +class SearchAllIamPoliciesResponse(proto.Message): + r"""Search all IAM policies response. + Attributes: + results (Sequence[google.cloud.asset_v1.types.IamPolicySearchResult]): + A list of IamPolicy 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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gca_assets.IamPolicySearchResult, + ) + next_page_token = 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 = 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 members 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 = 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 (Sequence[str]): + Optional. The roles to appear in result. + permissions (Sequence[str]): + Optional. The permissions to appear in + result. + """ + + roles = proto.RepeatedField( + proto.STRING, + number=1, + ) + permissions = 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. + + 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 GCP 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 resource cannot be used + together with this option. + + For example, if the request analyzes for which users have + permission P on a GCP project with this option enabled, the + results will include all users who have permission P on that + project or any lower resource. + + Default is false. + output_resource_edges (bool): + Optional. If true, the result will output + resource edges, starting from the policy + attached resource, to any expanded resources. + Default is false. + output_group_edges (bool): + Optional. If true, the result will output + group identity edges, starting from the + binding's group members, to any expanded + identities. 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 GCP folder F, then + user A potentially has access to the GCP 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 GCP 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 GCP folder F, + then user A potentially has access to the GCP 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]. + + Default is false. + """ + + expand_groups = proto.Field( + proto.BOOL, + number=1, + ) + expand_roles = proto.Field( + proto.BOOL, + number=2, + ) + expand_resources = proto.Field( + proto.BOOL, + number=3, + ) + output_resource_edges = proto.Field( + proto.BOOL, + number=4, + ) + output_group_edges = proto.Field( + proto.BOOL, + number=5, + ) + analyze_service_account_impersonation = proto.Field( + proto.BOOL, + number=6, + ) + + class ConditionContext(proto.Message): + r"""The IAM conditions context. + 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. + """ + + access_time = proto.Field( + proto.MESSAGE, + number=1, + oneof='TimeContext', + message=timestamp_pb2.Timestamp, + ) + + scope = proto.Field( + proto.STRING, + number=1, + ) + resource_selector = proto.Field( + proto.MESSAGE, + number=2, + message=ResourceSelector, + ) + identity_selector = proto.Field( + proto.MESSAGE, + number=3, + message=IdentitySelector, + ) + access_selector = proto.Field( + proto.MESSAGE, + number=4, + message=AccessSelector, + ) + options = proto.Field( + proto.MESSAGE, + number=5, + message=Options, + ) + condition_context = 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. + 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 = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + execution_timeout = 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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.asset_v1.types.IamPolicyAnalysisState]): + A list of non-critical errors happened during + the query handling. + """ + + analysis_query = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + analysis_results = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gca_assets.IamPolicyAnalysisResult, + ) + fully_explored = proto.Field( + proto.BOOL, + number=3, + ) + non_critical_errors = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=gca_assets.IamPolicyAnalysisState, + ) + + main_analysis = proto.Field( + proto.MESSAGE, + number=1, + message=IamPolicyAnalysis, + ) + service_account_impersonation_analysis = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=IamPolicyAnalysis, + ) + fully_explored = proto.Field( + proto.BOOL, + number=3, + ) + + +class IamPolicyAnalysisOutputConfig(proto.Message): + r"""Output configuration for export IAM policy analysis + destination. + + Attributes: + gcs_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.GcsDestination): + Destination on Cloud Storage. + bigquery_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.BigQueryDestination): + Destination on BigQuery. + """ + + 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 = 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. + """ + PARTITION_KEY_UNSPECIFIED = 0 + REQUEST_TIME = 1 + + dataset = proto.Field( + proto.STRING, + number=1, + ) + table_prefix = proto.Field( + proto.STRING, + number=2, + ) + partition_key = proto.Field( + proto.ENUM, + number=3, + enum='IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey', + ) + write_disposition = proto.Field( + proto.STRING, + number=4, + ) + + gcs_destination = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message=GcsDestination, + ) + bigquery_destination = 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. + output_config (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig): + Required. Output configuration indicating + where the results will be output to. + """ + + analysis_query = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + output_config = 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]. + """ + + +__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..b2b5a915 --- /dev/null +++ b/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py @@ -0,0 +1,1084 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore +from google.cloud.osconfig.v1 import inventory_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 +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', + 'ResourceSearchResult', + '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.""" + PRIOR_ASSET_STATE_UNSPECIFIED = 0 + PRESENT = 1 + INVALID = 2 + DOES_NOT_EXIST = 3 + DELETED = 4 + + window = proto.Field( + proto.MESSAGE, + number=1, + message='TimeWindow', + ) + deleted = proto.Field( + proto.BOOL, + number=2, + ) + asset = proto.Field( + proto.MESSAGE, + number=3, + message='Asset', + ) + prior_asset_state = proto.Field( + proto.ENUM, + number=4, + enum=PriorAssetState, + ) + prior_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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = 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. + Cloud IAM policy), or a relationship (e.g. an + INSTANCE_TO_INSTANCEGROUP relationship). See `Supported asset + types `__ + for more information. + + 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 Cloud IAM policy set on a Google + Cloud resource. There can be a maximum of one Cloud IAM + policy set on any given resource. In addition, Cloud 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 (Sequence[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 `__. + access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): + Please also refer to the `access level user + guide `__. + service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): + Please also refer to the `service perimeter user + guide `__. + os_inventory (google.cloud.osconfig.v1.inventory_pb2.Inventory): + A representation of runtime OS Inventory information. See + `this + topic `__ + for more information. + ancestors (Sequence[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 = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + name = proto.Field( + proto.STRING, + number=1, + ) + asset_type = proto.Field( + proto.STRING, + number=2, + ) + resource = proto.Field( + proto.MESSAGE, + number=3, + message='Resource', + ) + iam_policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + org_policy = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=orgpolicy_pb2.Policy, + ) + access_policy = proto.Field( + proto.MESSAGE, + number=7, + oneof='access_context_policy', + message=access_policy_pb2.AccessPolicy, + ) + access_level = proto.Field( + proto.MESSAGE, + number=8, + oneof='access_context_policy', + message=access_level_pb2.AccessLevel, + ) + service_perimeter = proto.Field( + proto.MESSAGE, + number=9, + oneof='access_context_policy', + message=service_perimeter_pb2.ServicePerimeter, + ) + os_inventory = proto.Field( + proto.MESSAGE, + number=12, + message=inventory_pb2.Inventory, + ) + ancestors = 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 `Cloud 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 = proto.Field( + proto.STRING, + number=1, + ) + discovery_document_uri = proto.Field( + proto.STRING, + number=2, + ) + discovery_name = proto.Field( + proto.STRING, + number=3, + ) + resource_url = proto.Field( + proto.STRING, + number=4, + ) + parent = proto.Field( + proto.STRING, + number=5, + ) + data = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + location = proto.Field( + proto.STRING, + number=8, + ) + + +class ResourceSearchResult(proto.Message): + r"""A result of Resource Search, containing information of a + cloud resource. + + 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 (Sequence[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 proto 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 proto 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 proto contains it. + + To search against the ``location``: + + - use a field query. Example: ``location:us-west*`` + - use a free text query. Example: ``us-west*`` + labels (Sequence[google.cloud.asset_v1.types.ResourceSearchResult.LabelsEntry]): + Labels associated with this resource. See `Labelling and + grouping GCP + resources `__ + for more information. This field is available only when the + resource's proto 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 (Sequence[str]): + Network tags associated with this resource. Like labels, + network tags are a type of annotations used to group GCP + resources. See `Labelling GCP + resources `__ + for more information. This field is available only when the + resource's proto 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 is available only when the resource's proto + contains it. + + To search against the ``kms_key``: + + - use a field query. Example: ``kmsKey: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 proto 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 proto 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 proto 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 Cloud 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 GCP 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 GCP 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`` + 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`` + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + asset_type = proto.Field( + proto.STRING, + number=2, + ) + project = proto.Field( + proto.STRING, + number=3, + ) + folders = proto.RepeatedField( + proto.STRING, + number=17, + ) + organization = proto.Field( + proto.STRING, + number=18, + ) + display_name = proto.Field( + proto.STRING, + number=4, + ) + description = proto.Field( + proto.STRING, + number=5, + ) + location = proto.Field( + proto.STRING, + number=6, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=7, + ) + network_tags = proto.RepeatedField( + proto.STRING, + number=8, + ) + kms_key = proto.Field( + proto.STRING, + number=10, + ) + create_time = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + update_time = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + state = proto.Field( + proto.STRING, + number=13, + ) + additional_attributes = proto.Field( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + parent_full_resource_name = proto.Field( + proto.STRING, + number=19, + ) + parent_asset_type = proto.Field( + proto.STRING, + number=103, + ) + + +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 GCP 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 (Sequence[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 (Sequence[google.cloud.asset_v1.types.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): + 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 (Sequence[str]): + A list of permissions. A sample permission string: + ``compute.disk.get``. + """ + + permissions = proto.RepeatedField( + proto.STRING, + number=1, + ) + + matched_permissions = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='IamPolicySearchResult.Explanation.Permissions', + ) + + resource = proto.Field( + proto.STRING, + number=1, + ) + asset_type = proto.Field( + proto.STRING, + number=5, + ) + project = proto.Field( + proto.STRING, + number=2, + ) + folders = proto.RepeatedField( + proto.STRING, + number=6, + ) + organization = proto.Field( + proto.STRING, + number=7, + ) + policy = proto.Field( + proto.MESSAGE, + number=3, + message=policy_pb2.Policy, + ) + 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 = proto.Field( + proto.ENUM, + number=1, + enum=code_pb2.Code, + ) + cause = 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.""" + EVALUATION_VALUE_UNSPECIFIED = 0 + TRUE = 1 + FALSE = 2 + CONDITIONAL = 3 + + evaluation_value = 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 Cloud IAM policy binding under analysis. + access_control_lists (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + analysis_state = proto.Field( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisState', + ) + + class Access(proto.Message): + r"""An IAM role or permission under analysis. + Attributes: + role (str): + The role. + permission (str): + The permission. + analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): + The analysis state of this access. + """ + + role = proto.Field( + proto.STRING, + number=1, + oneof='oneof_access', + ) + permission = proto.Field( + proto.STRING, + number=2, + oneof='oneof_access', + ) + analysis_state = proto.Field( + proto.MESSAGE, + number=3, + message='IamPolicyAnalysisState', + ) + + class Identity(proto.Message): + r"""An identity under analysis. + Attributes: + name (str): + The identity name in any form of members appear in `IAM + policy + binding `__, + such as: + + - user:foo@google.com + - group:group1@google.com + - serviceAccount:s1@prj1.iam.gserviceaccount.com + - projectOwner:some_project_id + - domain:google.com + - allUsers + - etc. + analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): + The analysis state of this identity. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + analysis_state = 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 = proto.Field( + proto.STRING, + number=1, + ) + target_node = 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 (Sequence[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 (Sequence[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 (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisResult.Resource', + ) + accesses = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.Access', + ) + resource_edges = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='IamPolicyAnalysisResult.Edge', + ) + condition_evaluation = proto.Field( + proto.MESSAGE, + number=4, + message='ConditionEvaluation', + ) + + class IdentityList(proto.Message): + r"""The identities and group edges. + Attributes: + identities (Sequence[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 (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisResult.Identity', + ) + group_edges = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.Edge', + ) + + attached_resource_full_name = proto.Field( + proto.STRING, + number=1, + ) + iam_binding = proto.Field( + proto.MESSAGE, + number=2, + message=policy_pb2.Binding, + ) + access_control_lists = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AccessControlList, + ) + identity_list = proto.Field( + proto.MESSAGE, + number=4, + message=IdentityList, + ) + fully_explored = 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..4505b485 --- /dev/null +++ b/owl-bot-staging/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +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..15e45490 --- /dev/null +++ b/owl-bot-staging/v1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/asset_v1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + 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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) 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..4a9e79e9 --- /dev/null +++ b/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py @@ -0,0 +1,187 @@ +#! /usr/bin/env python3 +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', 'execution_timeout', ), + 'analyze_iam_policy_longrunning': ('analysis_query', 'output_config', ), + 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', ), + 'create_feed': ('parent', 'feed_id', 'feed', ), + 'delete_feed': ('name', ), + 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', ), + 'get_feed': ('name', ), + 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), + 'list_feeds': ('parent', ), + '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', ), + '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: not a.keyword.value 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..1aece31b --- /dev/null +++ b/owl-bot-staging/v1/setup.py @@ -0,0 +1,53 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-asset', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..5d5e291d --- /dev/null +++ b/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py @@ -0,0 +1,4046 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +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_async # type: ignore +from google.api_core import operations_v1 +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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.asset_v1.types import asset_service +from google.cloud.asset_v1.types import assets +from google.longrunning import operations_pb2 +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.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + ] + 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"), +]) +@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(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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + # 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() + + # 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() + + # 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) + 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, + ) + +@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"), +]) +@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) + + 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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + 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, + ) + + +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, + ) + + +def test_export_assets(transport: str = 'grpc', request_type=asset_service.ExportAssetsRequest): + 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_from_dict(): + test_export_assets(request_type=dict) + + +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'] + + +def test_list_assets(transport: str = 'grpc', request_type=asset_service.ListAssetsRequest): + 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_from_dict(): + test_list_assets(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.Asset) + for i in results) + +def test_list_assets_pages(): + 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: + # 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: + 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 = [] + async for page_ in (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 + +def test_batch_get_assets_history(transport: str = 'grpc', request_type=asset_service.BatchGetAssetsHistoryRequest): + 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_from_dict(): + test_batch_get_assets_history(request_type=dict) + + +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'] + + +def test_create_feed(transport: str = 'grpc', request_type=asset_service.CreateFeedRequest): + 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_from_dict(): + test_create_feed(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_get_feed(transport: str = 'grpc', request_type=asset_service.GetFeedRequest): + 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_from_dict(): + test_get_feed(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_list_feeds(transport: str = 'grpc', request_type=asset_service.ListFeedsRequest): + 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_from_dict(): + test_list_feeds(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_update_feed(transport: str = 'grpc', request_type=asset_service.UpdateFeedRequest): + 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_from_dict(): + test_update_feed(request_type=dict) + + +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 = 'feed.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=feed.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 = 'feed.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=feed.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] + assert args[0].feed == asset_service.Feed(name='name_value') + + +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] + assert args[0].feed == asset_service.Feed(name='name_value') + + +@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'), + ) + + +def test_delete_feed(transport: str = 'grpc', request_type=asset_service.DeleteFeedRequest): + 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_from_dict(): + test_delete_feed(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_search_all_resources(transport: str = 'grpc', request_type=asset_service.SearchAllResourcesRequest): + 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_from_dict(): + test_search_all_resources(request_type=dict) + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + assert args[0].asset_types == ['asset_types_value'] + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + assert args[0].asset_types == ['asset_types_value'] + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.ResourceSearchResult) + for i in results) + +def test_search_all_resources_pages(): + 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: + # 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: + 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 = [] + async for page_ in (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 + +def test_search_all_iam_policies(transport: str = 'grpc', request_type=asset_service.SearchAllIamPoliciesRequest): + 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_from_dict(): + test_search_all_iam_policies(request_type=dict) + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) + for i in results) + +def test_search_all_iam_policies_pages(): + 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: + # 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: + 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 = [] + async for page_ in (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 + +def test_analyze_iam_policy(transport: str = 'grpc', request_type=asset_service.AnalyzeIamPolicyRequest): + 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_from_dict(): + test_analyze_iam_policy(request_type=dict) + + +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 = 'analysis_query.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=analysis_query.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 = 'analysis_query.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=analysis_query.scope/value', + ) in kw['metadata'] + + +def test_analyze_iam_policy_longrunning(transport: str = 'grpc', request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): + 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_from_dict(): + test_analyze_iam_policy_longrunning(request_type=dict) + + +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 = 'analysis_query.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=analysis_query.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 = 'analysis_query.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=analysis_query.scope/value', + ) in kw['metadata'] + + +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 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, +]) +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() + +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', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # 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=( + '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() + + +@requires_google_auth_gte_1_25_0 +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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # 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=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@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_host_no_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:8000' + +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_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 = "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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc new file mode 100644 index 00000000..3425850c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound 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/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..d0875802 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Asset v1p1beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p1beta1.types + :members: + :undoc-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..3aa26721 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-asset" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-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 = [ + ( + master_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 = [ + ( + master_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 = [ + ( + master_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..7f1c3781 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py @@ -0,0 +1,37 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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/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..7f5126b4 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py @@ -0,0 +1,38 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .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..175cd294 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/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_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" + ] + } + } + } + } + } + } +} 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..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..357f9520 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..58f4c63c --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py @@ -0,0 +1,403 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # 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 .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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: 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: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesAsyncPager: + r"""Searches all the resources under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under 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 it will be rejected. + + Args: + request (:class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest`): + 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:`Sequence[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. + # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesAsyncPager: + r"""Searches all the IAM policies under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under 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 it will be rejected. + + Args: + request (:class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest`): + 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. + # Sanity 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..5e6c3745 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py @@ -0,0 +1,567 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +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 .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport, None] = None, + client_options: Optional[client_options_lib.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 (google.api_core.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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: + 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: + 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, + ) + + def search_all_resources(self, + request: asset_service.SearchAllResourcesRequest = None, + *, + scope: str = None, + query: str = None, + asset_types: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllResourcesPager: + r"""Searches all the resources under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under 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 it will be rejected. + + Args: + request (google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest): + 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 (Sequence[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. + # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, + *, + scope: str = None, + query: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.SearchAllIamPoliciesPager: + r"""Searches all the IAM policies under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under 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 it will be rejected. + + Args: + request (google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest): + 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. + # Sanity 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..c8df82b2 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py @@ -0,0 +1,263 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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..2c12069f --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', +) 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..2b949ef9 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py @@ -0,0 +1,196 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-asset', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +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: 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, + **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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, 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) + + # If the credentials is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + 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, + ), + } + + @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() + + +__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..c906b681 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,291 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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 .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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> 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 applicatin 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 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 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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: ga_credentials.Credentials = None, + credentials_file: 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 under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under 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 it 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 under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under 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 it 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'] + + +__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..e04b788e --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,295 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1p1beta1.types import asset_service +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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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 applicatin 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 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 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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 under a given accessible + CRM scope (project/folder/organization). This RPC gives + callers especially admins the ability to search all the + resources under 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 it 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 under a given + accessible CRM scope (project/folder/organization). This + RPC gives callers especially admins the ability to + search all the IAM policies under 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 it 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'] + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) 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..c7f5d9a4 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py @@ -0,0 +1,36 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..2216599b --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py @@ -0,0 +1,205 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[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, " foo , bar desc ". + """ + + scope = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=3, + ) + page_size = proto.Field( + proto.INT32, + number=4, + ) + page_token = proto.Field( + proto.STRING, + number=5, + ) + order_by = proto.Field( + proto.STRING, + number=10, + ) + + +class SearchAllResourcesResponse(proto.Message): + r"""Search all resources response. + Attributes: + results (Sequence[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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=assets.StandardResourceMetadata, + ) + next_page_token = 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 = proto.Field( + proto.STRING, + number=1, + ) + query = proto.Field( + proto.STRING, + number=2, + ) + page_size = proto.Field( + proto.INT32, + number=3, + ) + page_token = proto.Field( + proto.STRING, + number=4, + ) + + +class SearchAllIamPoliciesResponse(proto.Message): + r"""Search all IAM policies response. + Attributes: + results (Sequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult]): + A list of IamPolicy 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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=assets.IamPolicySearchResult, + ) + next_page_token = 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..a351622a --- /dev/null +++ b/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py @@ -0,0 +1,193 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 (Sequence[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- + ast1", or zonal like "us-west1-b". + labels (Sequence[google.cloud.asset_v1p1beta1.types.StandardResourceMetadata.LabelsEntry]): + Labels associated with this resource. See `Labelling and + grouping GCP + resources `__ + for more information. + network_tags (Sequence[str]): + Network tags associated with this resource. Like labels, + network tags are a type of annotations used to group GCP + resources. See `Labelling GCP + resources `__ + for more information. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + asset_type = proto.Field( + proto.STRING, + number=2, + ) + project = proto.Field( + proto.STRING, + number=3, + ) + display_name = proto.Field( + proto.STRING, + number=4, + ) + description = proto.Field( + proto.STRING, + number=5, + ) + additional_attributes = proto.RepeatedField( + proto.STRING, + number=10, + ) + location = proto.Field( + proto.STRING, + number=11, + ) + labels = proto.MapField( + proto.STRING, + proto.STRING, + number=12, + ) + network_tags = proto.RepeatedField( + proto.STRING, + number=13, + ) + + +class IamPolicySearchResult(proto.Message): + r"""The result for a 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 GCP 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, the project field will be empty. + 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. + explanation (google.cloud.asset_v1p1beta1.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 (Sequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): + The map from roles to their included permission matching the + permission query (e.g. containing + ``policy.role.permissions:``). A sample 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 = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message='Permissions', + ) + + resource = proto.Field( + proto.STRING, + number=1, + ) + project = proto.Field( + proto.STRING, + number=3, + ) + policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + explanation = proto.Field( + proto.MESSAGE, + number=5, + message=Explanation, + ) + + +class Permissions(proto.Message): + r"""IAM permissions + Attributes: + permissions (Sequence[str]): + A list of permissions. A sample permission + string: "compute.disk.get". + """ + + permissions = 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..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +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..0c3db615 --- /dev/null +++ b/owl-bot-staging/v1p1beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/asset_v1p1beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + 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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) 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..dc77c201 --- /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 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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: not a.keyword.value 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..1aece31b --- /dev/null +++ b/owl-bot-staging/v1p1beta1/setup.py @@ -0,0 +1,53 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-asset', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..883e9d6d --- /dev/null +++ b/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -0,0 +1,1766 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +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.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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.asset_v1p1beta1.types import asset_service +from google.cloud.asset_v1p1beta1.types import assets +from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + ] + 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"), +]) +@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(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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + # 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() + + # 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() + + # 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) + 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, + ) + +@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"), +]) +@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) + + 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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + 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, + ) + + +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, + ) + + +def test_search_all_resources(transport: str = 'grpc', request_type=asset_service.SearchAllResourcesRequest): + 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_from_dict(): + test_search_all_resources(request_type=dict) + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + assert args[0].asset_types == ['asset_types_value'] + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + assert args[0].asset_types == ['asset_types_value'] + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.StandardResourceMetadata) + for i in results) + +def test_search_all_resources_pages(): + 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: + # 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: + 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 = [] + async for page_ in (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 + +def test_search_all_iam_policies(transport: str = 'grpc', request_type=asset_service.SearchAllIamPoliciesRequest): + 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_from_dict(): + test_search_all_iam_policies(request_type=dict) + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + + +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] + assert args[0].scope == 'scope_value' + assert args[0].query == 'query_value' + + +@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(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.IamPolicySearchResult) + for i in results) + +def test_search_all_iam_policies_pages(): + 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: + # 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: + 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 = [] + async for page_ in (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 + + +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 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, +]) +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() + +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()) + + +@requires_google_auth_gte_1_25_0 +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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # 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=( + '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() + + +@requires_google_auth_gte_1_25_0 +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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # 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=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@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_host_no_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:8000' + +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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p2beta1/.coveragerc b/owl-bot-staging/v1p2beta1/.coveragerc new file mode 100644 index 00000000..3425850c --- /dev/null +++ b/owl-bot-staging/v1p2beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound 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/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..b83adc35 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Asset v1p2beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p2beta1.types + :members: + :undoc-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..3aa26721 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-asset" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-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 = [ + ( + master_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 = [ + ( + master_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 = [ + ( + master_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..d7ceebac --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py @@ -0,0 +1,55 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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/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..6395a04b --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py @@ -0,0 +1,56 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .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..3c3674a8 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json @@ -0,0 +1,73 @@ + { + "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" + ] + } + } + } + } + } + } +} 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..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..357f9520 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..517d56f6 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py @@ -0,0 +1,578 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 .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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: 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: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (:class:`google.cloud.asset_v1p2beta1.types.CreateFeedRequest`): + 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. + # Sanity 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: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (:class:`google.cloud.asset_v1p2beta1.types.GetFeedRequest`): + 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. + # Sanity 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: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (:class:`google.cloud.asset_v1p2beta1.types.ListFeedsRequest`): + 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. + # Sanity 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: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (:class:`google.cloud.asset_v1p2beta1.types.UpdateFeedRequest`): + 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. + # Sanity 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: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (:class:`google.cloud.asset_v1p2beta1.types.DeleteFeedRequest`): + 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. + # Sanity 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..fbcbbad8 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py @@ -0,0 +1,744 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +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 + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport, None] = None, + client_options: Optional[client_options_lib.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 (google.api_core.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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: + 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: + 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, + ) + + def create_feed(self, + request: asset_service.CreateFeedRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Creates a feed in a parent + project/folder/organization to listen to its asset + updates. + + Args: + request (google.cloud.asset_v1p2beta1.types.CreateFeedRequest): + 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. + # Sanity 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: asset_service.GetFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Gets details about an asset feed. + + Args: + request (google.cloud.asset_v1p2beta1.types.GetFeedRequest): + 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. + # Sanity 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: asset_service.ListFeedsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.ListFeedsResponse: + r"""Lists all asset feeds in a parent + project/folder/organization. + + Args: + request (google.cloud.asset_v1p2beta1.types.ListFeedsRequest): + 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. + # Sanity 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: asset_service.UpdateFeedRequest = None, + *, + feed: asset_service.Feed = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.Feed: + r"""Updates an asset feed configuration. + + Args: + request (google.cloud.asset_v1p2beta1.types.UpdateFeedRequest): + 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. + # Sanity 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: asset_service.DeleteFeedRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes an asset feed. + + Args: + request (google.cloud.asset_v1p2beta1.types.DeleteFeedRequest): + 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. + # Sanity 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, + ) + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..2c12069f --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', +) 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..4c996833 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py @@ -0,0 +1,246 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-asset', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +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: 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, + **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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, 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) + + # If the credentials is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + 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, + ), + } + + @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() + + +__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..e81ab2e3 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,360 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> 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 applicatin 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 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 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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: ga_credentials.Credentials = None, + credentials_file: 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'] + + +__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..ed18d544 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,364 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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 applicatin 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 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 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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'] + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) 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..e4c38794 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py @@ -0,0 +1,54 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..8a7fa6c7 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py @@ -0,0 +1,310 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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.""" + 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 = proto.Field( + proto.STRING, + number=1, + ) + feed_id = proto.Field( + proto.STRING, + number=2, + ) + 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 = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class ListFeedsResponse(proto.Message): + r""" + Attributes: + feeds (Sequence[google.cloud.asset_v1p2beta1.types.Feed]): + A list of feeds. + """ + + feeds = 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 = proto.Field( + proto.MESSAGE, + number=1, + message='Feed', + ) + update_mask = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class OutputConfig(proto.Message): + r"""Output configuration for export assets destination. + Attributes: + gcs_destination (google.cloud.asset_v1p2beta1.types.GcsDestination): + Destination on Cloud Storage. + """ + + gcs_destination = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message='GcsDestination', + ) + + +class GcsDestination(proto.Message): + r"""A Cloud Storage location. + 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. + """ + + uri = 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 = proto.Field( + proto.STRING, + number=1, + ) + + +class FeedOutputConfig(proto.Message): + r"""Output configuration for asset feed destination. + Attributes: + pubsub_destination (google.cloud.asset_v1p2beta1.types.PubsubDestination): + Destination on Cloud Pubsub. + """ + + pubsub_destination = 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 (Sequence[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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + asset_names = proto.RepeatedField( + proto.STRING, + number=2, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + feed_output_config = 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..766824af --- /dev/null +++ b/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py @@ -0,0 +1,212 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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 = proto.Field( + proto.MESSAGE, + number=1, + message='TimeWindow', + ) + deleted = proto.Field( + proto.BOOL, + number=2, + ) + 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 = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time = 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 (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + asset_type = proto.Field( + proto.STRING, + number=2, + ) + resource = proto.Field( + proto.MESSAGE, + number=3, + message='Resource', + ) + iam_policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + ancestors = 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 = proto.Field( + proto.STRING, + number=1, + ) + discovery_document_uri = proto.Field( + proto.STRING, + number=2, + ) + discovery_name = proto.Field( + proto.STRING, + number=3, + ) + resource_url = proto.Field( + proto.STRING, + number=4, + ) + parent = proto.Field( + proto.STRING, + number=5, + ) + data = 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..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +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..bde1730c --- /dev/null +++ b/owl-bot-staging/v1p2beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/asset_v1p2beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + 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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) 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..cb36113c --- /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 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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: not a.keyword.value 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..1aece31b --- /dev/null +++ b/owl-bot-staging/v1p2beta1/setup.py @@ -0,0 +1,53 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-asset', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1p2beta1/tests/__init__.py b/owl-bot-staging/v1p2beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..6e097b89 --- /dev/null +++ b/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -0,0 +1,2115 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +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.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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION +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 + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + ] + 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"), +]) +@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(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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + # 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() + + # 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() + + # 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) + 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, + ) + +@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"), +]) +@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) + + 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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + 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, + ) + + +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, + ) + + +def test_create_feed(transport: str = 'grpc', request_type=asset_service.CreateFeedRequest): + 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_from_dict(): + test_create_feed(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_get_feed(transport: str = 'grpc', request_type=asset_service.GetFeedRequest): + 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_from_dict(): + test_get_feed(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +def test_list_feeds(transport: str = 'grpc', request_type=asset_service.ListFeedsRequest): + 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_from_dict(): + test_list_feeds(request_type=dict) + + +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] + assert args[0].parent == 'parent_value' + + +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] + assert args[0].parent == 'parent_value' + + +@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', + ) + + +def test_update_feed(transport: str = 'grpc', request_type=asset_service.UpdateFeedRequest): + 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_from_dict(): + test_update_feed(request_type=dict) + + +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 = 'feed.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=feed.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 = 'feed.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=feed.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] + assert args[0].feed == asset_service.Feed(name='name_value') + + +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] + assert args[0].feed == asset_service.Feed(name='name_value') + + +@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'), + ) + + +def test_delete_feed(transport: str = 'grpc', request_type=asset_service.DeleteFeedRequest): + 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_from_dict(): + test_delete_feed(request_type=dict) + + +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] + assert args[0].name == 'name_value' + + +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] + assert args[0].name == 'name_value' + + +@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', + ) + + +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 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, +]) +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() + +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()) + + +@requires_google_auth_gte_1_25_0 +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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # 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=( + '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() + + +@requires_google_auth_gte_1_25_0 +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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # 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=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@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_host_no_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:8000' + +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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p4beta1/.coveragerc b/owl-bot-staging/v1p4beta1/.coveragerc new file mode 100644 index 00000000..3425850c --- /dev/null +++ b/owl-bot-staging/v1p4beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p4beta1/MANIFEST.in b/owl-bot-staging/v1p4beta1/MANIFEST.in new file mode 100644 index 00000000..128f583b --- /dev/null +++ b/owl-bot-staging/v1p4beta1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/asset *.py +recursive-include google/cloud/asset_v1p4beta1 *.py diff --git a/owl-bot-staging/v1p4beta1/README.rst b/owl-bot-staging/v1p4beta1/README.rst new file mode 100644 index 00000000..110d4086 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/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/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst new file mode 100644 index 00000000..e46e3c5e --- /dev/null +++ b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst @@ -0,0 +1,6 @@ +AssetService +------------------------------ + +.. automodule:: google.cloud.asset_v1p4beta1.services.asset_service + :members: + :inherited-members: diff --git a/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst new file mode 100644 index 00000000..6116177f --- /dev/null +++ b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Asset v1p4beta1 API +============================================= +.. toctree:: + :maxdepth: 2 + + asset_service diff --git a/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst new file mode 100644 index 00000000..60ea41e5 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Asset v1p4beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p4beta1.types + :members: + :undoc-members: + :show-inheritance: diff --git a/owl-bot-staging/v1p4beta1/docs/conf.py b/owl-bot-staging/v1p4beta1/docs/conf.py new file mode 100644 index 00000000..3aa26721 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-asset" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-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 = [ + ( + master_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 = [ + ( + master_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 = [ + ( + master_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/v1p4beta1/docs/index.rst b/owl-bot-staging/v1p4beta1/docs/index.rst new file mode 100644 index 00000000..d944a266 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + asset_v1p4beta1/services + asset_v1p4beta1/types diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py new file mode 100644 index 00000000..4f1ec674 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py @@ -0,0 +1,37 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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_v1p4beta1.services.asset_service.client import AssetServiceClient +from google.cloud.asset_v1p4beta1.services.asset_service.async_client import AssetServiceAsyncClient + +from google.cloud.asset_v1p4beta1.types.asset_service import AnalyzeIamPolicyRequest +from google.cloud.asset_v1p4beta1.types.asset_service import AnalyzeIamPolicyResponse +from google.cloud.asset_v1p4beta1.types.asset_service import ExportIamPolicyAnalysisRequest +from google.cloud.asset_v1p4beta1.types.asset_service import ExportIamPolicyAnalysisResponse +from google.cloud.asset_v1p4beta1.types.asset_service import IamPolicyAnalysisOutputConfig +from google.cloud.asset_v1p4beta1.types.asset_service import IamPolicyAnalysisQuery +from google.cloud.asset_v1p4beta1.types.assets import IamPolicyAnalysisResult + +__all__ = ('AssetServiceClient', + 'AssetServiceAsyncClient', + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'ExportIamPolicyAnalysisRequest', + 'ExportIamPolicyAnalysisResponse', + 'IamPolicyAnalysisOutputConfig', + 'IamPolicyAnalysisQuery', + 'IamPolicyAnalysisResult', +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p4beta1/google/cloud/asset/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/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/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py new file mode 100644 index 00000000..a36f107c --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py @@ -0,0 +1,38 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + +from .types.asset_service import AnalyzeIamPolicyRequest +from .types.asset_service import AnalyzeIamPolicyResponse +from .types.asset_service import ExportIamPolicyAnalysisRequest +from .types.asset_service import ExportIamPolicyAnalysisResponse +from .types.asset_service import IamPolicyAnalysisOutputConfig +from .types.asset_service import IamPolicyAnalysisQuery +from .types.assets import IamPolicyAnalysisResult + +__all__ = ( + 'AssetServiceAsyncClient', +'AnalyzeIamPolicyRequest', +'AnalyzeIamPolicyResponse', +'AssetServiceClient', +'ExportIamPolicyAnalysisRequest', +'ExportIamPolicyAnalysisResponse', +'IamPolicyAnalysisOutputConfig', +'IamPolicyAnalysisQuery', +'IamPolicyAnalysisResult', +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/gapic_metadata.json b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/gapic_metadata.json new file mode 100644 index 00000000..23a2f8a3 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/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_v1p4beta1", + "protoPackage": "google.cloud.asset.v1p4beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "ExportIamPolicyAnalysis": { + "methods": [ + "export_iam_policy_analysis" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "ExportIamPolicyAnalysis": { + "methods": [ + "export_iam_policy_analysis" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/py.typed b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/py.typed new file mode 100644 index 00000000..3dbb09a3 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/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/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py new file mode 100644 index 00000000..357f9520 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py new file mode 100644 index 00000000..ba071f94 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py @@ -0,0 +1,298 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.asset_v1p4beta1.types import asset_service +from google.cloud.asset_v1p4beta1.types import assets +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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: 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 analyze_iam_policy(self, + request: asset_service.AnalyzeIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + Args: + request (:class:`google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest`): + The request object. A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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_v1p4beta1.types.AnalyzeIamPolicyResponse: + A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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.parent", request.analysis_query.parent), + )), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def export_iam_policy_analysis(self, + request: asset_service.ExportIamPolicyAnalysisRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Args: + request (:class:`google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest`): + The request object. A request message for + [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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_v1p4beta1.types.ExportIamPolicyAnalysisResponse` The export IAM policy analysis response. This message is returned by the + [google.longrunning.Operations.GetOperation][] method + in the returned + [google.longrunning.Operation.response][] field. + + """ + # Create or coerce a protobuf request object. + request = asset_service.ExportIamPolicyAnalysisRequest(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_iam_policy_analysis, + 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.parent", request.analysis_query.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.ExportIamPolicyAnalysisResponse, + metadata_type=asset_service.ExportIamPolicyAnalysisRequest, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AssetServiceAsyncClient", +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py new file mode 100644 index 00000000..3e2d7472 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py @@ -0,0 +1,472 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.asset_v1p4beta1.types import asset_service +from google.cloud.asset_v1p4beta1.types import assets +from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport, None] = None, + client_options: Optional[client_options_lib.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 (google.api_core.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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: + 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: + 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, + ) + + def analyze_iam_policy(self, + request: asset_service.AnalyzeIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> asset_service.AnalyzeIamPolicyResponse: + r"""Analyzes IAM policies based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + Args: + request (google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest): + The request object. A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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_v1p4beta1.types.AnalyzeIamPolicyResponse: + A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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.parent", request.analysis_query.parent), + )), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def export_iam_policy_analysis(self, + request: asset_service.ExportIamPolicyAnalysisRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Args: + request (google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest): + The request object. A request message for + [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (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_v1p4beta1.types.ExportIamPolicyAnalysisResponse` The export IAM policy analysis response. This message is returned by the + [google.longrunning.Operations.GetOperation][] method + in the returned + [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.ExportIamPolicyAnalysisRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, asset_service.ExportIamPolicyAnalysisRequest): + request = asset_service.ExportIamPolicyAnalysisRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_iam_policy_analysis] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("analysis_query.parent", request.analysis_query.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.ExportIamPolicyAnalysisResponse, + metadata_type=asset_service.ExportIamPolicyAnalysisRequest, + ) + + # Done; return the response. + return response + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ( + "AssetServiceClient", +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py new file mode 100644 index 00000000..2c12069f --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py new file mode 100644 index 00000000..2ed2d012 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py @@ -0,0 +1,195 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.asset_v1p4beta1.types import asset_service +from google.longrunning import operations_pb2 # type: ignore + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-asset', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +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: 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, + **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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, 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) + + # If the credentials is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + 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.export_iam_policy_analysis: gapic_v1.method.wrap_method( + self.export_iam_policy_analysis, + default_timeout=60.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def analyze_iam_policy(self) -> Callable[ + [asset_service.AnalyzeIamPolicyRequest], + Union[ + asset_service.AnalyzeIamPolicyResponse, + Awaitable[asset_service.AnalyzeIamPolicyResponse] + ]]: + raise NotImplementedError() + + @property + def export_iam_policy_analysis(self) -> Callable[ + [asset_service.ExportIamPolicyAnalysisRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + +__all__ = ( + 'AssetServiceTransport', +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py new file mode 100644 index 00000000..e76518e7 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,304 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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_v1p4beta1.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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> 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 applicatin 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 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 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 = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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: ga_credentials.Credentials = None, + credentials_file: 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. + """ + # Sanity 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 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 based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + 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.v1p4beta1.AssetService/AnalyzeIamPolicy', + request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, + response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, + ) + return self._stubs['analyze_iam_policy'] + + @property + def export_iam_policy_analysis(self) -> Callable[ + [asset_service.ExportIamPolicyAnalysisRequest], + operations_pb2.Operation]: + r"""Return a callable for the export iam policy analysis method over gRPC. + + Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Returns: + Callable[[~.ExportIamPolicyAnalysisRequest], + ~.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_iam_policy_analysis' not in self._stubs: + self._stubs['export_iam_policy_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis', + request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_iam_policy_analysis'] + + +__all__ = ( + 'AssetServiceGrpcTransport', +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..375ee7b5 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,308 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1p4beta1.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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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 applicatin 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 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 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 = 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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. + """ + # Sanity 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 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 based on the specified request. Returns a + list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] + matching the request. + + 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.v1p4beta1.AssetService/AnalyzeIamPolicy', + request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, + response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, + ) + return self._stubs['analyze_iam_policy'] + + @property + def export_iam_policy_analysis(self) -> Callable[ + [asset_service.ExportIamPolicyAnalysisRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the export iam policy analysis method over gRPC. + + Exports IAM policy analysis based on the specified request. This + API implements the + [google.longrunning.Operation][google.longrunning.Operation] API + allowing you to keep track of the export. The metadata contains + the request to help callers to map responses to requests. + + Returns: + Callable[[~.ExportIamPolicyAnalysisRequest], + 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_iam_policy_analysis' not in self._stubs: + self._stubs['export_iam_policy_analysis'] = self.grpc_channel.unary_unary( + '/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis', + request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['export_iam_policy_analysis'] + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py new file mode 100644 index 00000000..a2cfd26f --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py @@ -0,0 +1,36 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 ( + AnalyzeIamPolicyRequest, + AnalyzeIamPolicyResponse, + ExportIamPolicyAnalysisRequest, + ExportIamPolicyAnalysisResponse, + IamPolicyAnalysisOutputConfig, + IamPolicyAnalysisQuery, +) +from .assets import ( + IamPolicyAnalysisResult, +) + +__all__ = ( + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'ExportIamPolicyAnalysisRequest', + 'ExportIamPolicyAnalysisResponse', + 'IamPolicyAnalysisOutputConfig', + 'IamPolicyAnalysisQuery', + 'IamPolicyAnalysisResult', +) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py new file mode 100644 index 00000000..a7661b30 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py @@ -0,0 +1,534 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.cloud.asset_v1p4beta1.types import assets +from google.protobuf import duration_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p4beta1', + manifest={ + 'IamPolicyAnalysisQuery', + 'AnalyzeIamPolicyRequest', + 'AnalyzeIamPolicyResponse', + 'IamPolicyAnalysisOutputConfig', + 'ExportIamPolicyAnalysisRequest', + 'ExportIamPolicyAnalysisResponse', + }, +) + + +class IamPolicyAnalysisQuery(proto.Message): + r"""IAM policy analysis query message. + Attributes: + parent (str): + Required. The relative name of the root + asset. Only resources and IAM policies within + the parent will be analyzed. This can only be an + organization number (such as + "organizations/123") or a folder number (such as + "folders/123"). + resource_selector (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery.ResourceSelector): + Optional. Specifies a resource for analysis. + Leaving it empty means ANY. + identity_selector (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery.IdentitySelector): + Optional. Specifies an identity for analysis. + Leaving it empty means ANY. + access_selector (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery.AccessSelector): + Optional. Specifies roles or permissions for + analysis. Leaving it empty means ANY. + """ + + 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. At least one of + [ResourceSelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.ResourceSelector], + [IdentitySelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.IdentitySelector] + or + [AccessSelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.AccessSelector] + must be specified in a request. + + Attributes: + full_resource_name (str): + Required. The `full resource + name `__ + . + """ + + full_resource_name = 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 members in `IAM + policy + binding `__. + """ + + identity = 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 + identities and resources matching any of them. + + Attributes: + roles (Sequence[str]): + Optional. The roles to appear in result. + permissions (Sequence[str]): + Optional. The permissions to appear in + result. + """ + + roles = proto.RepeatedField( + proto.STRING, + number=1, + ) + permissions = proto.RepeatedField( + proto.STRING, + number=2, + ) + + parent = proto.Field( + proto.STRING, + number=1, + ) + resource_selector = proto.Field( + proto.MESSAGE, + number=2, + message=ResourceSelector, + ) + identity_selector = proto.Field( + proto.MESSAGE, + number=3, + message=IdentitySelector, + ) + access_selector = proto.Field( + proto.MESSAGE, + number=4, + message=AccessSelector, + ) + + +class AnalyzeIamPolicyRequest(proto.Message): + r"""A request message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + Attributes: + analysis_query (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery): + Required. The request query. + options (google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest.Options): + Optional. The request options. + """ + + class Options(proto.Message): + r"""Contains request 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 [identity_selector][] is specified, the identity in the + result will be determined by the selector, and this flag + will have no effect. + + 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 [access_selector][] is specified, the access section of + the result will be determined by the selector, and this flag + will have no effect. + + Default is false. + expand_resources (bool): + Optional. If true, 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 GCP folder, the results will also include + resources in that folder with permission P. + + If [resource_selector][] is specified, the resource section + of the result will be determined by the selector, and this + flag will have no effect. Default is false. + output_resource_edges (bool): + Optional. If true, the result will output + resource edges, starting from the policy + attached resource, to any expanded resources. + Default is false. + output_group_edges (bool): + Optional. If true, the result will output + group identity edges, starting from the + binding's group members, to any expanded + identities. 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 ExportIamPolicyAnalysis 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 GCP folder F, then + user A potentially has access to the GCP folder F. And those + advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Another example, if the request analyzes for who has + permission P to a GCP 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 GCP folder F, + then user A potentially has access to the GCP folder F. And + those advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Default is false. + 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. + """ + + expand_groups = proto.Field( + proto.BOOL, + number=1, + ) + expand_roles = proto.Field( + proto.BOOL, + number=2, + ) + expand_resources = proto.Field( + proto.BOOL, + number=3, + ) + output_resource_edges = proto.Field( + proto.BOOL, + number=4, + ) + output_group_edges = proto.Field( + proto.BOOL, + number=5, + ) + analyze_service_account_impersonation = proto.Field( + proto.BOOL, + number=6, + ) + execution_timeout = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + + analysis_query = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + options = proto.Field( + proto.MESSAGE, + number=2, + message=Options, + ) + + +class AnalyzeIamPolicyResponse(proto.Message): + r"""A response message for + [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. + + Attributes: + main_analysis (google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyResponse.IamPolicyAnalysis): + The main analysis that matches the original + request. + service_account_impersonation_analysis (Sequence[google.cloud.asset_v1p4beta1.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.v1p4beta1.AnalyzeIamPolicyResponse.main_analysis] + and + [service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis] + have been fully explored to answer the query in the request. + non_critical_errors (Sequence[google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState]): + A list of non-critical errors happened during the request + handling to explain why ``fully_explored`` is false, or + empty if no error happened. + """ + + class IamPolicyAnalysis(proto.Message): + r"""An analysis message to group the query and results. + Attributes: + analysis_query (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery): + The analysis query. + analysis_results (Sequence[google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult]): + A list of + [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.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.v1p4beta1.AnalyzeIamPolicyResponse.IamPolicyAnalysis.analysis_results] + have been fully explored to answer the query. + """ + + analysis_query = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + analysis_results = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=assets.IamPolicyAnalysisResult, + ) + fully_explored = proto.Field( + proto.BOOL, + number=3, + ) + + main_analysis = proto.Field( + proto.MESSAGE, + number=1, + message=IamPolicyAnalysis, + ) + service_account_impersonation_analysis = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=IamPolicyAnalysis, + ) + fully_explored = proto.Field( + proto.BOOL, + number=3, + ) + non_critical_errors = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=assets.IamPolicyAnalysisResult.AnalysisState, + ) + + +class IamPolicyAnalysisOutputConfig(proto.Message): + r"""Output configuration for export IAM policy analysis + destination. + + Attributes: + gcs_destination (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig.GcsDestination): + Destination on Cloud Storage. + """ + + 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. For example: + "gs://bucket_name/object_name". See `Viewing and Editing + Object + Metadata `__ + for more information. + """ + + uri = proto.Field( + proto.STRING, + number=1, + ) + + gcs_destination = proto.Field( + proto.MESSAGE, + number=1, + oneof='destination', + message=GcsDestination, + ) + + +class ExportIamPolicyAnalysisRequest(proto.Message): + r"""A request message for + [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. + + Attributes: + analysis_query (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery): + Required. The request query. + options (google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest.Options): + Optional. The request options. + output_config (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig): + Required. Output configuration indicating + where the results will be output to. + """ + + class Options(proto.Message): + r"""Contains request 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 [identity_selector][] is specified, the identity in the + result will be determined by the selector, and this flag + will have no effect. + + 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 [access_selector][] is specified, the access section of + the result will be determined by the selector, and this flag + will have no effect. + + Default is false. + expand_resources (bool): + Optional. If true, 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 GCP folder, the results will also include + resources in that folder with permission P. + + If [resource_selector][] is specified, the resource section + of the result will be determined by the selector, and this + flag will have no effect. Default is false. + output_resource_edges (bool): + Optional. If true, the result will output + resource edges, starting from the policy + attached resource, to any expanded resources. + Default is false. + output_group_edges (bool): + Optional. If true, the result will output + group identity edges, starting from the + binding's group members, to any expanded + identities. 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. + + 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 GCP folder F, then + user A potentially has access to the GCP folder F. And those + advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Another example, if the request analyzes for who has + permission P to a GCP 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 GCP folder F, + then user A potentially has access to the GCP folder F. And + those advanced analysis results will be included in + [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. + + Default is false. + """ + + expand_groups = proto.Field( + proto.BOOL, + number=1, + ) + expand_roles = proto.Field( + proto.BOOL, + number=2, + ) + expand_resources = proto.Field( + proto.BOOL, + number=3, + ) + output_resource_edges = proto.Field( + proto.BOOL, + number=4, + ) + output_group_edges = proto.Field( + proto.BOOL, + number=5, + ) + analyze_service_account_impersonation = proto.Field( + proto.BOOL, + number=6, + ) + + analysis_query = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisQuery', + ) + options = proto.Field( + proto.MESSAGE, + number=2, + message=Options, + ) + output_config = proto.Field( + proto.MESSAGE, + number=3, + message='IamPolicyAnalysisOutputConfig', + ) + + +class ExportIamPolicyAnalysisResponse(proto.Message): + r"""The export IAM policy analysis response. This message is returned by + the [google.longrunning.Operations.GetOperation][] method in the + returned [google.longrunning.Operation.response][] field. + + Attributes: + output_config (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig): + Output configuration indicating where the + results were output to. + """ + + output_config = proto.Field( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisOutputConfig', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py new file mode 100644 index 00000000..e3f1607d --- /dev/null +++ b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py @@ -0,0 +1,302 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 proto # type: ignore + +from google.iam.v1 import policy_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.asset.v1p4beta1', + manifest={ + 'IamPolicyAnalysisResult', + }, +) + + +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 name of the resource to which the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + policy attaches. + iam_binding (google.iam.v1.policy_pb2.Binding): + The Cloud IAM policy binding under analysis. + access_control_lists (Sequence[google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AccessControlList]): + The access control lists derived from the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + that match or potentially match resource and access + selectors specified in the request. + identity_list (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.IdentityList): + The identity list derived from members of the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + that match or potentially match identity selector specified + in the request. + fully_explored (bool): + Represents whether all nodes in the transitive closure of + the + [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] + node have been explored. + """ + + class AnalysisState(proto.Message): + r"""Represents analysis state of each node in the result graph or + non-critical errors in the response. + + Attributes: + code (google.rpc.code_pb2.Code): + The Google standard error code that best describes the + state. For example: + + - OK means the node has been successfully explored; + - PERMISSION_DENIED means an access denied error is + encountered; + - DEADLINE_EXCEEDED means the node hasn't been explored in + time; + cause (str): + The human-readable description of the cause + of failure. + """ + + code = proto.Field( + proto.ENUM, + number=1, + enum=code_pb2.Code, + ) + cause = proto.Field( + proto.STRING, + number=2, + ) + + class Resource(proto.Message): + r"""A GCP resource that appears in an access control list. + Attributes: + full_resource_name (str): + The `full resource + name `__. + analysis_state (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState): + The analysis state of this resource node. + """ + + full_resource_name = proto.Field( + proto.STRING, + number=1, + ) + analysis_state = proto.Field( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.AnalysisState', + ) + + class Access(proto.Message): + r"""A role or permission that appears in an access control list. + Attributes: + role (str): + The role. + permission (str): + The permission. + analysis_state (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState): + The analysis state of this access node. + """ + + role = proto.Field( + proto.STRING, + number=1, + oneof='oneof_access', + ) + permission = proto.Field( + proto.STRING, + number=2, + oneof='oneof_access', + ) + analysis_state = proto.Field( + proto.MESSAGE, + number=3, + message='IamPolicyAnalysisResult.AnalysisState', + ) + + class Edge(proto.Message): + r"""A directional edge. + Attributes: + source_node (str): + The source node of the edge. + target_node (str): + The target node of the edge. + """ + + source_node = proto.Field( + proto.STRING, + number=1, + ) + target_node = proto.Field( + proto.STRING, + number=2, + ) + + class Identity(proto.Message): + r"""An identity that appears in an access control list. + Attributes: + name (str): + The identity name in any form of members appear in `IAM + policy + binding `__, + such as: + + - user:foo@google.com + - group:group1@google.com + - serviceAccount:s1@prj1.iam.gserviceaccount.com + - projectOwner:some_project_id + - domain:google.com + - allUsers + - etc. + analysis_state (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState): + The analysis state of this identity node. + """ + + name = proto.Field( + proto.STRING, + number=1, + ) + analysis_state = proto.Field( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.AnalysisState', + ) + + 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 (Sequence[google.cloud.asset_v1p4beta1.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 (Sequence[google.cloud.asset_v1p4beta1.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 (Sequence[google.cloud.asset_v1p4beta1.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.v1p4beta1.IamPolicyAnalysisResult.Edge.source_node] + contains the full resource name of a parent resource and + [Edge.target_node][google.cloud.asset.v1p4beta1.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. + """ + + resources = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisResult.Resource', + ) + accesses = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.Access', + ) + resource_edges = proto.RepeatedField( + proto.MESSAGE, + number=3, + message='IamPolicyAnalysisResult.Edge', + ) + + class IdentityList(proto.Message): + r""" + Attributes: + identities (Sequence[google.cloud.asset_v1p4beta1.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 (Sequence[google.cloud.asset_v1p4beta1.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.v1p4beta1.IamPolicyAnalysisResult.IdentityList.identities]. + The + [Edge.source_node][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.source_node] + contains a group, such as "group:parent@google.com". The + [Edge.target_node][google.cloud.asset.v1p4beta1.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 = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='IamPolicyAnalysisResult.Identity', + ) + group_edges = proto.RepeatedField( + proto.MESSAGE, + number=2, + message='IamPolicyAnalysisResult.Edge', + ) + + attached_resource_full_name = proto.Field( + proto.STRING, + number=1, + ) + iam_binding = proto.Field( + proto.MESSAGE, + number=2, + message=policy_pb2.Binding, + ) + access_control_lists = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=AccessControlList, + ) + identity_list = proto.Field( + proto.MESSAGE, + number=4, + message=IdentityList, + ) + fully_explored = proto.Field( + proto.BOOL, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p4beta1/mypy.ini b/owl-bot-staging/v1p4beta1/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/owl-bot-staging/v1p4beta1/noxfile.py b/owl-bot-staging/v1p4beta1/noxfile.py new file mode 100644 index 00000000..f7008fb0 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/asset_v1p4beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + 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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) diff --git a/owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py b/owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py new file mode 100644 index 00000000..b3ee3fcb --- /dev/null +++ b/owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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', 'options', ), + 'export_iam_policy_analysis': ('analysis_query', 'output_config', 'options', ), + } + + 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: not a.keyword.value 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/v1p4beta1/setup.py b/owl-bot-staging/v1p4beta1/setup.py new file mode 100644 index 00000000..1aece31b --- /dev/null +++ b/owl-bot-staging/v1p4beta1/setup.py @@ -0,0 +1,53 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-asset', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1p4beta1/tests/__init__.py b/owl-bot-staging/v1p4beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p4beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1p4beta1/tests/unit/__init__.py b/owl-bot-staging/v1p4beta1/tests/unit/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p4beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1p4beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p4beta1/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p4beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py b/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py b/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py new file mode 100644 index 00000000..dcc13156 --- /dev/null +++ b/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py @@ -0,0 +1,1254 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +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_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceAsyncClient +from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceClient +from google.cloud.asset_v1p4beta1.services.asset_service import transports +from google.cloud.asset_v1p4beta1.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.asset_v1p4beta1.types import asset_service +from google.cloud.asset_v1p4beta1.types import assets +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + ] + 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"), +]) +@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(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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + # 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() + + # 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() + + # 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) + 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, + ) + +@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"), +]) +@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) + + 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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + 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, + ) + + +def test_asset_service_client_client_options_from_dict(): + with mock.patch('google.cloud.asset_v1p4beta1.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, + ) + + +def test_analyze_iam_policy(transport: str = 'grpc', request_type=asset_service.AnalyzeIamPolicyRequest): + 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_from_dict(): + test_analyze_iam_policy(request_type=dict) + + +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.parent = 'analysis_query.parent/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.parent=analysis_query.parent/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.parent = 'analysis_query.parent/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.parent=analysis_query.parent/value', + ) in kw['metadata'] + + +def test_export_iam_policy_analysis(transport: str = 'grpc', request_type=asset_service.ExportIamPolicyAnalysisRequest): + 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_iam_policy_analysis), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.export_iam_policy_analysis(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.ExportIamPolicyAnalysisRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_iam_policy_analysis_from_dict(): + test_export_iam_policy_analysis(request_type=dict) + + +def test_export_iam_policy_analysis_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_iam_policy_analysis), + '__call__') as call: + client.export_iam_policy_analysis() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == asset_service.ExportIamPolicyAnalysisRequest() + + +@pytest.mark.asyncio +async def test_export_iam_policy_analysis_async(transport: str = 'grpc_asyncio', request_type=asset_service.ExportIamPolicyAnalysisRequest): + 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_iam_policy_analysis), + '__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_iam_policy_analysis(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.ExportIamPolicyAnalysisRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_iam_policy_analysis_async_from_dict(): + await test_export_iam_policy_analysis_async(request_type=dict) + + +def test_export_iam_policy_analysis_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.ExportIamPolicyAnalysisRequest() + + request.analysis_query.parent = 'analysis_query.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_iam_policy_analysis), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.export_iam_policy_analysis(request) + + # Establish that the 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.parent=analysis_query.parent/value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_export_iam_policy_analysis_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.ExportIamPolicyAnalysisRequest() + + request.analysis_query.parent = 'analysis_query.parent/value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.export_iam_policy_analysis), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.export_iam_policy_analysis(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.parent=analysis_query.parent/value', + ) in kw['metadata'] + + +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 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, +]) +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() + +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_v1p4beta1.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 = ( + 'analyze_iam_policy', + 'export_iam_policy_analysis', + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +@requires_google_auth_gte_1_25_0 +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_v1p4beta1.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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # 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_v1p4beta1.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=( + '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_v1p4beta1.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() + + +@requires_google_auth_gte_1_25_0 +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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # 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=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@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_host_no_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:8000' + +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_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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p5beta1/.coveragerc b/owl-bot-staging/v1p5beta1/.coveragerc new file mode 100644 index 00000000..3425850c --- /dev/null +++ b/owl-bot-staging/v1p5beta1/.coveragerc @@ -0,0 +1,17 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/asset/__init__.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound 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/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..31650c9a --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst @@ -0,0 +1,7 @@ +Types for Google Cloud Asset v1p5beta1 API +========================================== + +.. automodule:: google.cloud.asset_v1p5beta1.types + :members: + :undoc-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..3aa26721 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 = "1.6.3" + +# 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 master toctree document. +master_doc = "index" + +# General information about the project. +project = u"google-cloud-asset" +copyright = u"2020, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-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 = [ + ( + master_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 = [ + ( + master_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 = [ + ( + master_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..a84dfdea --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.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/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..b6d6b65b --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py @@ -0,0 +1,34 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 .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..3d280aa7 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "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" + ] + } + } + } + } + } + } +} 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..4de65971 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..357f9520 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..05e2db9c --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py @@ -0,0 +1,237 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # 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 .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 + + asset_path = staticmethod(AssetServiceClient.asset_path) + parse_asset_path = staticmethod(AssetServiceClient.parse_asset_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 + + @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: ga_credentials.Credentials = None, + transport: Union[str, AssetServiceTransport] = "grpc_asyncio", + client_options: 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: asset_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + Args: + request (:class:`google.cloud.asset_v1p5beta1.types.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: + 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. + request = asset_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..1ebfd59d --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py @@ -0,0 +1,418 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +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 .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AssetServiceGrpcTransport +from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport + + +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 + + def get_transport_class(cls, + label: 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 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 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 {} + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, AssetServiceTransport, None] = None, + client_options: Optional[client_options_lib.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 (google.api_core.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. + 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() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) + + client_cert_source_func = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + is_mtls = True + client_cert_source_func = client_options.client_cert_source + else: + is_mtls = mtls.has_default_client_cert_source() + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" + ) + + # 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: + 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: + 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, + ) + + def list_assets(self, + request: asset_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists assets with time and resource types and returns + paged results in response. + + Args: + request (google.cloud.asset_v1p5beta1.types.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: + 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. + # 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) + + # 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 + + + + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-asset", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__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..13ea4412 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py @@ -0,0 +1,141 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional + +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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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..2c12069f --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py @@ -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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] +_transport_registry['grpc'] = AssetServiceGrpcTransport +_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport + +__all__ = ( + 'AssetServiceTransport', + 'AssetServiceGrpcTransport', + 'AssetServiceGrpcAsyncIOTransport', +) 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..757cf600 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py @@ -0,0 +1,175 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import packaging.version +import pkg_resources + +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +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 + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + 'google-cloud-asset', + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + + +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: 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, + **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. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + scopes_kwargs = self._get_scopes_kwargs(self._host, 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) + + # If the credentials is 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 + + # TODO(busunkim): This method is in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-auth is increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + 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, + ), + } + + @property + def list_assets(self) -> Callable[ + [asset_service.ListAssetsRequest], + Union[ + asset_service.ListAssetsResponse, + Awaitable[asset_service.ListAssetsResponse] + ]]: + 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..40fdf10e --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py @@ -0,0 +1,253 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import gapic_v1 # type: ignore +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 .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: ga_credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: 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, + ) -> 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 applicatin 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 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 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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: ga_credentials.Credentials = None, + credentials_file: 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'] + + +__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..49dc7185 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py @@ -0,0 +1,257 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.asset_v1p5beta1.types import asset_service +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: 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: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + ) -> 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 applicatin 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 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 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, + ) + + if not self._grpc_channel: + self._grpc_channel = type(self).create_channel( + self._host, + credentials=self._credentials, + credentials_file=credentials_file, + 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'] + + +__all__ = ( + 'AssetServiceGrpcAsyncIOTransport', +) 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..5f29a3d9 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py @@ -0,0 +1,32 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..301f423f --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py @@ -0,0 +1,140 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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.""" + 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-number]" + (such as "projects/my-project-id"), or + "projects/[project-id]" (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 2018-10-02 + UTC (inclusive) and the current time. 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 (Sequence[str]): + A list of asset types of which to take a snapshot for. For + example: "compute.googleapis.com/Disk". If specified, only + matching assets will be returned. 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 = proto.Field( + proto.STRING, + number=1, + ) + read_time = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + asset_types = proto.RepeatedField( + proto.STRING, + number=3, + ) + content_type = proto.Field( + proto.ENUM, + number=4, + enum='ContentType', + ) + page_size = proto.Field( + proto.INT32, + number=5, + ) + page_token = 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 (Sequence[google.cloud.asset_v1p5beta1.types.Asset]): + Assets. + next_page_token (str): + Token to retrieve the next page of results. + Set to empty if there are no remaining results. + """ + + @property + def raw_page(self): + return self + + read_time = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + assets = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=gca_assets.Asset, + ) + next_page_token = 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..79781961 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py @@ -0,0 +1,194 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 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"""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_v1p5beta1.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. + org_policy (Sequence[google.cloud.orgpolicy.v1.orgpolicy_pb2.Policy]): + Representation of the Cloud Organization + Policy set on an asset. For each asset, there + could be multiple Organization policies with + different constraints. + access_policy (google.identity.accesscontextmanager.v1.access_policy_pb2.AccessPolicy): + + access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): + + service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): + + ancestors (Sequence[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 = proto.Field( + proto.STRING, + number=1, + ) + asset_type = proto.Field( + proto.STRING, + number=2, + ) + resource = proto.Field( + proto.MESSAGE, + number=3, + message='Resource', + ) + iam_policy = proto.Field( + proto.MESSAGE, + number=4, + message=policy_pb2.Policy, + ) + org_policy = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=orgpolicy_pb2.Policy, + ) + access_policy = proto.Field( + proto.MESSAGE, + number=7, + oneof='access_context_policy', + message=access_policy_pb2.AccessPolicy, + ) + access_level = proto.Field( + proto.MESSAGE, + number=8, + oneof='access_context_policy', + message=access_level_pb2.AccessLevel, + ) + service_perimeter = proto.Field( + proto.MESSAGE, + number=9, + oneof='access_context_policy', + message=service_perimeter_pb2.ServicePerimeter, + ) + ancestors = proto.RepeatedField( + proto.STRING, + number=10, + ) + + +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 = proto.Field( + proto.STRING, + number=1, + ) + discovery_document_uri = proto.Field( + proto.STRING, + number=2, + ) + discovery_name = proto.Field( + proto.STRING, + number=3, + ) + resource_url = proto.Field( + proto.STRING, + number=4, + ) + parent = proto.Field( + proto.STRING, + number=5, + ) + data = 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..4505b485 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +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..e1a406a9 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/noxfile.py @@ -0,0 +1,132 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +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") + + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", +] + +@nox.session(python=['3.6', '3.7', '3.8', '3.9']) +def unit(session): + """Run the unit test suite.""" + + session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') + session.install('-e', '.') + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/asset_v1p5beta1/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)) + ) + + +@nox.session(python='3.7') +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=['3.6', '3.7']) +def mypy(session): + """Run the type checker.""" + session.install('mypy', 'types-pkg_resources') + 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='3.6') +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx<3.0.0", "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", ""), + ) 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..9eb4f0f8 --- /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 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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: not a.keyword.value 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..1aece31b --- /dev/null +++ b/owl-bot-staging/v1p5beta1/setup.py @@ -0,0 +1,53 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +version = '0.1.0' + +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() + +setuptools.setup( + name='google-cloud-asset', + version=version, + long_description=readme, + packages=setuptools.PEP420PackageFinder.find(), + namespace_packages=('google', 'google.cloud'), + platforms='Posix; MacOS X; Windows', + include_package_data=True, + install_requires=( + 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', + 'libcst >= 0.2.5', + 'proto-plus >= 1.15.0', + 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), + python_requires='>=3.6', + classifiers=[ + 'Development Status :: 3 - Alpha', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Topic :: Internet', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + zip_safe=False, +) diff --git a/owl-bot-staging/v1p5beta1/tests/__init__.py b/owl-bot-staging/v1p5beta1/tests/__init__.py new file mode 100644 index 00000000..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..b54a5fcc --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py @@ -0,0 +1,16 @@ + +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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..6e4c0b98 --- /dev/null +++ b/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -0,0 +1,1266 @@ +# -*- 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 +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 mock +import packaging.version + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + + +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.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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION +from google.cloud.asset_v1p5beta1.types import asset_service +from google.cloud.asset_v1p5beta1.types import assets +from google.oauth2 import service_account +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +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", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_info(client_class): + 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) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_service_account_always_use_jwt_true(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) + + +@pytest.mark.parametrize("client_class", [ + AssetServiceClient, + AssetServiceAsyncClient, +]) +def test_asset_service_client_from_service_account_file(client_class): + 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") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_client_get_transport_class(): + transport = AssetServiceClient.get_transport_class() + available_transports = [ + transports.AssetServiceGrpcTransport, + ] + 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"), +]) +@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(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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + # 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() + + # 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() + + # 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) + 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, + ) + +@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"), +]) +@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) + + 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, + ) + + # 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() + 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, + ) + + # 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() + 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, + ) + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +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) + 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, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), + (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), +]) +def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): + # 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) + 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, + ) + + +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, + ) + + +def test_list_assets(transport: str = 'grpc', request_type=asset_service.ListAssetsRequest): + 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_from_dict(): + test_list_assets(request_type=dict) + + +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_pager(): + 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: + # 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 = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, assets.Asset) + for i in results) + +def test_list_assets_pages(): + 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: + # 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: + 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 = [] + async for page_ in (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 + + +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 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, +]) +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() + +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()) + + +@requires_google_auth_gte_1_25_0 +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", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # 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=( + '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() + + +@requires_google_auth_gte_1_25_0 +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, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # 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=( 'https://www.googleapis.com/auth/cloud-platform',), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +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, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(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") + adc.assert_called_once_with(scopes=( + 'https://www.googleapis.com/auth/cloud-platform', +), + quota_project_id="octopus", + ) + + +@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_host_no_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:443' + + +def test_asset_service_host_with_port(): + client = AssetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), + ) + assert client.transport._host == 'cloudasset.googleapis.com:8000' + +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_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_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_withDEFAULT_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) From fb7344f8b357b5472af7675527208d969ebb9023 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 29 Jun 2021 22:36:36 +0000 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/master/packages/owl-bot/README.md --- .coveragerc | 1 - .../services/asset_service/async_client.py | 14 +- .../asset_v1/services/asset_service/client.py | 4 + .../services/asset_service/transports/base.py | 52 +- .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 10 +- google/cloud/asset_v1/types/asset_service.py | 39 + google/cloud/asset_v1/types/assets.py | 32 + .../services/asset_service/transports/base.py | 42 +- .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 10 +- .../services/asset_service/transports/base.py | 42 +- .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 10 +- .../services/asset_service/transports/base.py | 42 +- .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 10 +- .../services/asset_service/transports/base.py | 42 +- .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 10 +- owl-bot-staging/v1/.coveragerc | 17 - owl-bot-staging/v1/MANIFEST.in | 2 - owl-bot-staging/v1/README.rst | 49 - .../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 | 7 - owl-bot-staging/v1/docs/conf.py | 376 -- owl-bot-staging/v1/docs/index.rst | 7 - .../v1/google/cloud/asset/__init__.py | 105 - .../v1/google/cloud/asset/py.typed | 2 - .../v1/google/cloud/asset_v1/__init__.py | 106 - .../google/cloud/asset_v1/gapic_metadata.json | 143 - .../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 | 1316 ------ .../asset_v1/services/asset_service/client.py | 1463 ------ .../asset_v1/services/asset_service/pagers.py | 385 -- .../asset_service/transports/__init__.py | 33 - .../services/asset_service/transports/base.py | 383 -- .../services/asset_service/transports/grpc.py | 598 --- .../asset_service/transports/grpc_asyncio.py | 602 --- .../google/cloud/asset_v1/types/__init__.py | 104 - .../cloud/asset_v1/types/asset_service.py | 1700 ------- .../v1/google/cloud/asset_v1/types/assets.py | 1084 ----- owl-bot-staging/v1/mypy.ini | 3 - owl-bot-staging/v1/noxfile.py | 132 - .../v1/scripts/fixup_asset_v1_keywords.py | 187 - owl-bot-staging/v1/setup.py | 53 - 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 | 4046 ----------------- owl-bot-staging/v1p1beta1/.coveragerc | 17 - owl-bot-staging/v1p1beta1/MANIFEST.in | 2 - owl-bot-staging/v1p1beta1/README.rst | 49 - .../docs/asset_v1p1beta1/asset_service.rst | 10 - .../docs/asset_v1p1beta1/services.rst | 6 - .../v1p1beta1/docs/asset_v1p1beta1/types.rst | 7 - owl-bot-staging/v1p1beta1/docs/conf.py | 376 -- owl-bot-staging/v1p1beta1/docs/index.rst | 7 - .../v1p1beta1/google/cloud/asset/__init__.py | 37 - .../v1p1beta1/google/cloud/asset/py.typed | 2 - .../google/cloud/asset_v1p1beta1/__init__.py | 38 - .../cloud/asset_v1p1beta1/gapic_metadata.json | 43 - .../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 | 403 -- .../services/asset_service/client.py | 567 --- .../services/asset_service/pagers.py | 263 -- .../asset_service/transports/__init__.py | 33 - .../services/asset_service/transports/base.py | 196 - .../services/asset_service/transports/grpc.py | 291 -- .../asset_service/transports/grpc_asyncio.py | 295 -- .../cloud/asset_v1p1beta1/types/__init__.py | 36 - .../asset_v1p1beta1/types/asset_service.py | 205 - .../cloud/asset_v1p1beta1/types/assets.py | 193 - owl-bot-staging/v1p1beta1/mypy.ini | 3 - owl-bot-staging/v1p1beta1/noxfile.py | 132 - .../scripts/fixup_asset_v1p1beta1_keywords.py | 177 - owl-bot-staging/v1p1beta1/setup.py | 53 - 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 | 1766 ------- owl-bot-staging/v1p2beta1/.coveragerc | 17 - owl-bot-staging/v1p2beta1/MANIFEST.in | 2 - owl-bot-staging/v1p2beta1/README.rst | 49 - .../docs/asset_v1p2beta1/asset_service.rst | 6 - .../docs/asset_v1p2beta1/services.rst | 6 - .../v1p2beta1/docs/asset_v1p2beta1/types.rst | 7 - owl-bot-staging/v1p2beta1/docs/conf.py | 376 -- owl-bot-staging/v1p2beta1/docs/index.rst | 7 - .../v1p2beta1/google/cloud/asset/__init__.py | 55 - .../v1p2beta1/google/cloud/asset/py.typed | 2 - .../google/cloud/asset_v1p2beta1/__init__.py | 56 - .../cloud/asset_v1p2beta1/gapic_metadata.json | 73 - .../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 | 578 --- .../services/asset_service/client.py | 744 --- .../asset_service/transports/__init__.py | 33 - .../services/asset_service/transports/base.py | 246 - .../services/asset_service/transports/grpc.py | 360 -- .../asset_service/transports/grpc_asyncio.py | 364 -- .../cloud/asset_v1p2beta1/types/__init__.py | 54 - .../asset_v1p2beta1/types/asset_service.py | 310 -- .../cloud/asset_v1p2beta1/types/assets.py | 212 - owl-bot-staging/v1p2beta1/mypy.ini | 3 - owl-bot-staging/v1p2beta1/noxfile.py | 132 - .../scripts/fixup_asset_v1p2beta1_keywords.py | 180 - owl-bot-staging/v1p2beta1/setup.py | 53 - 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 | 2115 --------- owl-bot-staging/v1p4beta1/.coveragerc | 17 - owl-bot-staging/v1p4beta1/MANIFEST.in | 2 - owl-bot-staging/v1p4beta1/README.rst | 49 - .../docs/asset_v1p4beta1/asset_service.rst | 6 - .../docs/asset_v1p4beta1/services.rst | 6 - .../v1p4beta1/docs/asset_v1p4beta1/types.rst | 7 - owl-bot-staging/v1p4beta1/docs/conf.py | 376 -- owl-bot-staging/v1p4beta1/docs/index.rst | 7 - .../v1p4beta1/google/cloud/asset/__init__.py | 37 - .../v1p4beta1/google/cloud/asset/py.typed | 2 - .../google/cloud/asset_v1p4beta1/__init__.py | 38 - .../cloud/asset_v1p4beta1/gapic_metadata.json | 43 - .../google/cloud/asset_v1p4beta1/py.typed | 2 - .../asset_v1p4beta1/services/__init__.py | 15 - .../services/asset_service/__init__.py | 22 - .../services/asset_service/async_client.py | 298 -- .../services/asset_service/client.py | 472 -- .../asset_service/transports/__init__.py | 33 - .../services/asset_service/transports/base.py | 195 - .../services/asset_service/transports/grpc.py | 304 -- .../asset_service/transports/grpc_asyncio.py | 308 -- .../cloud/asset_v1p4beta1/types/__init__.py | 36 - .../asset_v1p4beta1/types/asset_service.py | 534 --- .../cloud/asset_v1p4beta1/types/assets.py | 302 -- owl-bot-staging/v1p4beta1/mypy.ini | 3 - owl-bot-staging/v1p4beta1/noxfile.py | 132 - .../scripts/fixup_asset_v1p4beta1_keywords.py | 177 - owl-bot-staging/v1p4beta1/setup.py | 53 - owl-bot-staging/v1p4beta1/tests/__init__.py | 16 - .../v1p4beta1/tests/unit/__init__.py | 16 - .../v1p4beta1/tests/unit/gapic/__init__.py | 16 - .../unit/gapic/asset_v1p4beta1/__init__.py | 16 - .../asset_v1p4beta1/test_asset_service.py | 1254 ----- owl-bot-staging/v1p5beta1/.coveragerc | 17 - owl-bot-staging/v1p5beta1/MANIFEST.in | 2 - owl-bot-staging/v1p5beta1/README.rst | 49 - .../docs/asset_v1p5beta1/asset_service.rst | 10 - .../docs/asset_v1p5beta1/services.rst | 6 - .../v1p5beta1/docs/asset_v1p5beta1/types.rst | 7 - owl-bot-staging/v1p5beta1/docs/conf.py | 376 -- owl-bot-staging/v1p5beta1/docs/index.rst | 7 - .../v1p5beta1/google/cloud/asset/__init__.py | 33 - .../v1p5beta1/google/cloud/asset/py.typed | 2 - .../google/cloud/asset_v1p5beta1/__init__.py | 34 - .../cloud/asset_v1p5beta1/gapic_metadata.json | 33 - .../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 | 237 - .../services/asset_service/client.py | 418 -- .../services/asset_service/pagers.py | 141 - .../asset_service/transports/__init__.py | 33 - .../services/asset_service/transports/base.py | 175 - .../services/asset_service/transports/grpc.py | 253 -- .../asset_service/transports/grpc_asyncio.py | 257 -- .../cloud/asset_v1p5beta1/types/__init__.py | 32 - .../asset_v1p5beta1/types/asset_service.py | 140 - .../cloud/asset_v1p5beta1/types/assets.py | 194 - owl-bot-staging/v1p5beta1/mypy.ini | 3 - owl-bot-staging/v1p5beta1/noxfile.py | 132 - .../scripts/fixup_asset_v1p5beta1_keywords.py | 176 - owl-bot-staging/v1p5beta1/setup.py | 53 - 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 | 1266 ------ scripts/fixup_asset_v1_keywords.py | 2 +- .../unit/gapic/asset_v1/test_asset_service.py | 126 +- .../asset_v1p1beta1/test_asset_service.py | 126 +- .../asset_v1p2beta1/test_asset_service.py | 126 +- .../asset_v1p4beta1/test_asset_service.py | 126 +- .../asset_v1p5beta1/test_asset_service.py | 126 +- 194 files changed, 403 insertions(+), 34097 deletions(-) delete mode 100644 owl-bot-staging/v1/.coveragerc 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/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/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/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/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/scripts/fixup_asset_v1_keywords.py delete mode 100644 owl-bot-staging/v1/setup.py 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/MANIFEST.in delete mode 100644 owl-bot-staging/v1p1beta1/README.rst 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/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/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/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/scripts/fixup_asset_v1p1beta1_keywords.py delete mode 100644 owl-bot-staging/v1p1beta1/setup.py 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/MANIFEST.in delete mode 100644 owl-bot-staging/v1p2beta1/README.rst 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/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/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/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/scripts/fixup_asset_v1p2beta1_keywords.py delete mode 100644 owl-bot-staging/v1p2beta1/setup.py 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/v1p4beta1/.coveragerc delete mode 100644 owl-bot-staging/v1p4beta1/MANIFEST.in delete mode 100644 owl-bot-staging/v1p4beta1/README.rst delete mode 100644 owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst delete mode 100644 owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst delete mode 100644 owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst delete mode 100644 owl-bot-staging/v1p4beta1/docs/conf.py delete mode 100644 owl-bot-staging/v1p4beta1/docs/index.rst delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset/py.typed delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/gapic_metadata.json delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/py.typed delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py delete mode 100644 owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py delete mode 100644 owl-bot-staging/v1p4beta1/mypy.ini delete mode 100644 owl-bot-staging/v1p4beta1/noxfile.py delete mode 100644 owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py delete mode 100644 owl-bot-staging/v1p4beta1/setup.py delete mode 100644 owl-bot-staging/v1p4beta1/tests/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py delete mode 100644 owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py delete mode 100644 owl-bot-staging/v1p5beta1/.coveragerc 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/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/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/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/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/scripts/fixup_asset_v1p5beta1_keywords.py delete mode 100644 owl-bot-staging/v1p5beta1/setup.py 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/.coveragerc b/.coveragerc index 86c446a3..3425850c 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,7 +2,6 @@ branch = True [report] -fail_under = 100 show_missing = True omit = google/cloud/asset/__init__.py diff --git a/google/cloud/asset_v1/services/asset_service/async_client.py b/google/cloud/asset_v1/services/asset_service/async_client.py index b4d9fcc2..b56b0f30 100644 --- a/google/cloud/asset_v1/services/asset_service/async_client.py +++ b/google/cloud/asset_v1/services/asset_service/async_client.py @@ -955,12 +955,11 @@ async def search_all_resources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), - deadline=15.0, + deadline=30.0, ), - default_timeout=15.0, + default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, ) @@ -1067,6 +1066,10 @@ async def search_all_iam_policies( 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 "user" member type. This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this @@ -1113,12 +1116,11 @@ async def search_all_iam_policies( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), - deadline=15.0, + deadline=30.0, ), - default_timeout=15.0, + default_timeout=30.0, client_info=DEFAULT_CLIENT_INFO, ) diff --git a/google/cloud/asset_v1/services/asset_service/client.py b/google/cloud/asset_v1/services/asset_service/client.py index 54151fb8..b2b3245c 100644 --- a/google/cloud/asset_v1/services/asset_service/client.py +++ b/google/cloud/asset_v1/services/asset_service/client.py @@ -1194,6 +1194,10 @@ def search_all_iam_policies( 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 "user" member type. This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this diff --git a/google/cloud/asset_v1/services/asset_service/transports/base.py b/google/cloud/asset_v1/services/asset_service/transports/base.py index 42793ee5..e15d7266 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -25,6 +25,7 @@ from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore 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 @@ -46,8 +47,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" @@ -65,6 +64,7 @@ def __init__( 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, **kwargs, ) -> None: """Instantiate the transport. @@ -88,6 +88,8 @@ def __init__( 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -97,7 +99,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. @@ -116,13 +118,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -143,27 +152,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -258,12 +246,11 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), - deadline=15.0, + deadline=30.0, ), - default_timeout=15.0, + default_timeout=30.0, client_info=client_info, ), self.search_all_iam_policies: gapic_v1.method.wrap_method( @@ -273,12 +260,11 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, core_exceptions.ServiceUnavailable, ), - deadline=15.0, + deadline=30.0, ), - default_timeout=15.0, + default_timeout=30.0, client_info=client_info, ), self.analyze_iam_policy: gapic_v1.method.wrap_method( diff --git a/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 6ca9e36a..177e4a3a 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -60,6 +60,7 @@ def __init__( client_cert_source_for_mtls: 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, ) -> None: """Instantiate the transport. @@ -100,6 +101,8 @@ def __init__( 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 @@ -153,6 +156,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -208,14 +212,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py index 96f1af84..7df1ccb4 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py @@ -81,14 +81,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -106,6 +106,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -147,6 +148,8 @@ def __init__( 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 @@ -199,6 +202,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/asset_v1/types/asset_service.py b/google/cloud/asset_v1/types/asset_service.py index 9f6a1854..bb0dd094 100644 --- a/google/cloud/asset_v1/types/asset_service.py +++ b/google/cloud/asset_v1/types/asset_service.py @@ -879,6 +879,10 @@ class SearchAllIamPoliciesRequest(proto.Message): - ``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 "user" member type. 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 @@ -892,12 +896,47 @@ class SearchAllIamPoliciesRequest(proto.Message): 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 (Sequence[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 = proto.Field(proto.STRING, number=1,) query = proto.Field(proto.STRING, number=2,) page_size = proto.Field(proto.INT32, number=3,) page_token = proto.Field(proto.STRING, number=4,) + asset_types = proto.RepeatedField(proto.STRING, number=5,) + order_by = proto.Field(proto.STRING, number=7,) class SearchAllIamPoliciesResponse(proto.Message): diff --git a/google/cloud/asset_v1/types/assets.py b/google/cloud/asset_v1/types/assets.py index 893f9c33..5778741c 100644 --- a/google/cloud/asset_v1/types/assets.py +++ b/google/cloud/asset_v1/types/assets.py @@ -518,6 +518,13 @@ class IamPolicySearchResult(proto.Message): - 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 GCP resource belongs to, in the form of projects/{PROJECT_NUMBER}. If an IAM policy is @@ -530,6 +537,28 @@ class IamPolicySearchResult(proto.Message): - specify the ``scope`` field as this project in your search request. + folders (Sequence[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 @@ -588,7 +617,10 @@ class Permissions(proto.Message): ) resource = proto.Field(proto.STRING, number=1,) + asset_type = proto.Field(proto.STRING, number=5,) project = proto.Field(proto.STRING, number=2,) + folders = proto.RepeatedField(proto.STRING, number=6,) + organization = proto.Field(proto.STRING, number=7,) policy = proto.Field(proto.MESSAGE, number=3, message=policy_pb2.Policy,) explanation = proto.Field(proto.MESSAGE, number=4, message=Explanation,) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py index 8ee42a9b..eb764427 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore 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 @@ -43,8 +44,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" @@ -62,6 +61,7 @@ def __init__( 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, **kwargs, ) -> None: """Instantiate the transport. @@ -85,6 +85,8 @@ def __init__( 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -94,7 +96,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. @@ -113,13 +115,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -140,27 +149,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py index 4b4b685f..5014c340 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( client_cert_source_for_mtls: 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, ) -> None: """Instantiate the transport. @@ -97,6 +98,8 @@ def __init__( 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 @@ -149,6 +152,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -204,14 +208,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py index a93fad9a..9b3b4bb7 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py @@ -78,14 +78,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -103,6 +103,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -144,6 +145,8 @@ def __init__( 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 @@ -195,6 +198,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py index 5d867d28..59950757 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore 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 @@ -44,8 +45,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" @@ -63,6 +62,7 @@ def __init__( 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, **kwargs, ) -> None: """Instantiate the transport. @@ -86,6 +86,8 @@ def __init__( 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -95,7 +97,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. @@ -114,13 +116,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -141,27 +150,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py index c6342408..1d41fd52 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py @@ -58,6 +58,7 @@ def __init__( client_cert_source_for_mtls: 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, ) -> None: """Instantiate the transport. @@ -98,6 +99,8 @@ def __init__( 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 @@ -150,6 +153,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -205,14 +209,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py index aaaa591f..aadf6a1a 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py @@ -79,14 +79,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -104,6 +104,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -145,6 +146,8 @@ def __init__( 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 @@ -196,6 +199,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py index 65d21b3f..01575ced 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py @@ -25,6 +25,7 @@ from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore from google.cloud.asset_v1p4beta1.types import asset_service from google.longrunning import operations_pb2 # type: ignore @@ -45,8 +46,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" @@ -64,6 +63,7 @@ def __init__( 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, **kwargs, ) -> None: """Instantiate the transport. @@ -87,6 +87,8 @@ def __init__( 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -96,7 +98,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. @@ -115,13 +117,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -142,27 +151,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py index e958a387..1113b5d4 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py @@ -59,6 +59,7 @@ def __init__( client_cert_source_for_mtls: 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, ) -> None: """Instantiate the transport. @@ -99,6 +100,8 @@ def __init__( 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 @@ -152,6 +155,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -207,14 +211,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py index 7005c0f4..c51ccc94 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py @@ -80,14 +80,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -105,6 +105,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -146,6 +147,8 @@ def __init__( 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 @@ -198,6 +201,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py index 1c877d77..2b5302ca 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py @@ -24,6 +24,7 @@ from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore 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 @@ -43,8 +44,6 @@ except pkg_resources.DistributionNotFound: # pragma: NO COVER _GOOGLE_AUTH_VERSION = None -_API_CORE_VERSION = google.api_core.__version__ - class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" @@ -62,6 +61,7 @@ def __init__( 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, **kwargs, ) -> None: """Instantiate the transport. @@ -85,6 +85,8 @@ def __init__( 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. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -94,7 +96,7 @@ def __init__( scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) # Save the scopes. - self._scopes = scopes or self.AUTH_SCOPES + self._scopes = scopes # If no credentials are provided, then determine the appropriate # defaults. @@ -113,13 +115,20 @@ def __init__( **scopes_kwargs, quota_project_id=quota_project_id ) + # If the credentials is 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 - # TODO(busunkim): These two class methods are in the base transport + # TODO(busunkim): This method is in the base transport # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-api-core - # and google-auth are increased. + # should be deleted once the minimum required versions of google-auth is increased. # TODO: Remove this function once google-auth >= 1.25.0 is required @classmethod @@ -140,27 +149,6 @@ def _get_scopes_kwargs( return scopes_kwargs - # TODO: Remove this function once google-api-core >= 1.26.0 is required - @classmethod - def _get_self_signed_jwt_kwargs( - cls, host: str, scopes: Optional[Sequence[str]] - ) -> Dict[str, Union[Optional[Sequence[str]], str]]: - """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" - - self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} - - if _API_CORE_VERSION and ( - packaging.version.parse(_API_CORE_VERSION) - >= packaging.version.parse("1.26.0") - ): - self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES - self_signed_jwt_kwargs["scopes"] = scopes - self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST - else: - self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES - - return self_signed_jwt_kwargs - def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py index 409c71bd..b5ac0ae5 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py @@ -57,6 +57,7 @@ def __init__( client_cert_source_for_mtls: 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, ) -> None: """Instantiate the transport. @@ -97,6 +98,8 @@ def __init__( 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 @@ -149,6 +152,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: @@ -204,14 +208,14 @@ def create_channel( and ``credentials_file`` are passed. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py index 41d9136c..3449feb6 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py @@ -78,14 +78,14 @@ def create_channel( aio.Channel: A gRPC AsyncIO channel object. """ - self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) - return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, - **self_signed_jwt_kwargs, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, **kwargs, ) @@ -103,6 +103,7 @@ def __init__( client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, ) -> None: """Instantiate the transport. @@ -144,6 +145,8 @@ def __init__( 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 @@ -195,6 +198,7 @@ def __init__( scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, + always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: diff --git a/owl-bot-staging/v1/.coveragerc b/owl-bot-staging/v1/.coveragerc deleted file mode 100644 index 3425850c..00000000 --- a/owl-bot-staging/v1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound 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/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 c75a1efd..00000000 --- a/owl-bot-staging/v1/docs/asset_v1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Asset v1 API -=================================== - -.. automodule:: google.cloud.asset_v1.types - :members: - :undoc-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 3aa26721..00000000 --- a/owl-bot-staging/v1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-asset" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-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 = [ - ( - master_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 = [ - ( - master_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 = [ - ( - master_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 815c196c..00000000 --- a/owl-bot-staging/v1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,105 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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 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 BatchGetAssetsHistoryRequest -from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryResponse -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 DeleteFeedRequest -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 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 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 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 UpdateFeedRequest -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 ConditionEvaluation -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 Resource -from google.cloud.asset_v1.types.assets import ResourceSearchResult -from google.cloud.asset_v1.types.assets import TemporalAsset -from google.cloud.asset_v1.types.assets import TimeWindow - -__all__ = ('AssetServiceClient', - 'AssetServiceAsyncClient', - 'AnalyzeIamPolicyLongrunningRequest', - 'AnalyzeIamPolicyLongrunningResponse', - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'BatchGetAssetsHistoryRequest', - 'BatchGetAssetsHistoryResponse', - 'BigQueryDestination', - 'CreateFeedRequest', - 'DeleteFeedRequest', - 'ExportAssetsRequest', - 'ExportAssetsResponse', - 'Feed', - 'FeedOutputConfig', - 'GcsDestination', - 'GcsOutputResult', - 'GetFeedRequest', - 'IamPolicyAnalysisOutputConfig', - 'IamPolicyAnalysisQuery', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'OutputConfig', - 'OutputResult', - 'PartitionSpec', - 'PubsubDestination', - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'UpdateFeedRequest', - 'ContentType', - 'Asset', - 'ConditionEvaluation', - 'IamPolicyAnalysisResult', - 'IamPolicyAnalysisState', - 'IamPolicySearchResult', - 'Resource', - 'ResourceSearchResult', - 'TemporalAsset', - 'TimeWindow', -) 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 35fdc066..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/__init__.py +++ /dev/null @@ -1,106 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .services.asset_service import AssetServiceClient -from .services.asset_service import AssetServiceAsyncClient - -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 BatchGetAssetsHistoryRequest -from .types.asset_service import BatchGetAssetsHistoryResponse -from .types.asset_service import BigQueryDestination -from .types.asset_service import CreateFeedRequest -from .types.asset_service import DeleteFeedRequest -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 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 OutputConfig -from .types.asset_service import OutputResult -from .types.asset_service import PartitionSpec -from .types.asset_service import PubsubDestination -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 UpdateFeedRequest -from .types.asset_service import ContentType -from .types.assets import Asset -from .types.assets import ConditionEvaluation -from .types.assets import IamPolicyAnalysisResult -from .types.assets import IamPolicyAnalysisState -from .types.assets import IamPolicySearchResult -from .types.assets import Resource -from .types.assets import ResourceSearchResult -from .types.assets import TemporalAsset -from .types.assets import TimeWindow - -__all__ = ( - 'AssetServiceAsyncClient', -'AnalyzeIamPolicyLongrunningRequest', -'AnalyzeIamPolicyLongrunningResponse', -'AnalyzeIamPolicyRequest', -'AnalyzeIamPolicyResponse', -'Asset', -'AssetServiceClient', -'BatchGetAssetsHistoryRequest', -'BatchGetAssetsHistoryResponse', -'BigQueryDestination', -'ConditionEvaluation', -'ContentType', -'CreateFeedRequest', -'DeleteFeedRequest', -'ExportAssetsRequest', -'ExportAssetsResponse', -'Feed', -'FeedOutputConfig', -'GcsDestination', -'GcsOutputResult', -'GetFeedRequest', -'IamPolicyAnalysisOutputConfig', -'IamPolicyAnalysisQuery', -'IamPolicyAnalysisResult', -'IamPolicyAnalysisState', -'IamPolicySearchResult', -'ListAssetsRequest', -'ListAssetsResponse', -'ListFeedsRequest', -'ListFeedsResponse', -'OutputConfig', -'OutputResult', -'PartitionSpec', -'PubsubDestination', -'Resource', -'ResourceSearchResult', -'SearchAllIamPoliciesRequest', -'SearchAllIamPoliciesResponse', -'SearchAllResourcesRequest', -'SearchAllResourcesResponse', -'TemporalAsset', -'TimeWindow', -'UpdateFeedRequest', -) 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 eebf25a1..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/gapic_metadata.json +++ /dev/null @@ -1,143 +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" - ] - }, - "BatchGetAssetsHistory": { - "methods": [ - "batch_get_assets_history" - ] - }, - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "ExportAssets": { - "methods": [ - "export_assets" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AssetServiceAsyncClient", - "rpcs": { - "AnalyzeIamPolicy": { - "methods": [ - "analyze_iam_policy" - ] - }, - "AnalyzeIamPolicyLongrunning": { - "methods": [ - "analyze_iam_policy_longrunning" - ] - }, - "BatchGetAssetsHistory": { - "methods": [ - "batch_get_assets_history" - ] - }, - "CreateFeed": { - "methods": [ - "create_feed" - ] - }, - "DeleteFeed": { - "methods": [ - "delete_feed" - ] - }, - "ExportAssets": { - "methods": [ - "export_assets" - ] - }, - "GetFeed": { - "methods": [ - "get_feed" - ] - }, - "ListAssets": { - "methods": [ - "list_assets" - ] - }, - "ListFeeds": { - "methods": [ - "list_feeds" - ] - }, - "SearchAllIamPolicies": { - "methods": [ - "search_all_iam_policies" - ] - }, - "SearchAllResources": { - "methods": [ - "search_all_resources" - ] - }, - "UpdateFeed": { - "methods": [ - "update_feed" - ] - } - } - } - } - } - } -} 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 4de65971..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 357f9520..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 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ab3d0f1b..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/async_client.py +++ /dev/null @@ -1,1316 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # 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.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 - - 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) - 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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: 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: asset_service.ExportAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 proto 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. - - Args: - request (:class:`google.cloud.asset_v1.types.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: - 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: asset_service.ListAssetsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - Args: - request (:class:`google.cloud.asset_v1.types.ListAssetsRequest`): - 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_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. - # Sanity 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: asset_service.BatchGetAssetsHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.asset_v1.types.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: - 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: asset_service.CreateFeedRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Args: - request (:class:`google.cloud.asset_v1.types.CreateFeedRequest`): - 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. - # Sanity 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: asset_service.GetFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - Args: - request (:class:`google.cloud.asset_v1.types.GetFeedRequest`): - 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. - # Sanity 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: asset_service.ListFeedsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - Args: - request (:class:`google.cloud.asset_v1.types.ListFeedsRequest`): - 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. - # Sanity 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: asset_service.UpdateFeedRequest = None, - *, - feed: asset_service.Feed = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - Args: - request (:class:`google.cloud.asset_v1.types.UpdateFeedRequest`): - 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. - # Sanity 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: asset_service.DeleteFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an asset feed. - - Args: - request (:class:`google.cloud.asset_v1.types.DeleteFeedRequest`): - 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. - # Sanity 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: asset_service.SearchAllResourcesRequest = None, - *, - scope: str = None, - query: str = None, - asset_types: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesAsyncPager: - r"""Searches all 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. - - Args: - request (:class:`google.cloud.asset_v1.types.SearchAllResourcesRequest`): - 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 Cloud resources whose name - contains "Important" as a word. - - ``name=Important`` to find the Cloud resource whose - name is exactly "Important". - - ``displayName:Impor*`` to find Cloud resources whose - display name contains "Impor" as a prefix of any word - in the field. - - ``location:us-west*`` to find Cloud resources whose - location contains both "us" and "west" as prefixes. - - ``labels:prod`` to find Cloud resources whose labels - contain "prod" as a key or value. - - ``labels.env:prod`` to find Cloud resources that have - a label "env" and its value is "prod". - - ``labels.env:*`` to find Cloud resources that have a - label "env". - - ``kmsKey:key`` to find Cloud resources encrypted with - a customer-managed encryption key whose name contains - the word "key". - - ``state:ACTIVE`` to find Cloud resources whose state - contains "ACTIVE" as a word. - - ``NOT state:ACTIVE`` to find {{gcp_name}} resources - whose state doesn't contain "ACTIVE" as a word. - - ``createTime<1609459200`` to find 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 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 Cloud resources that contain - "Important" as a word in any of the searchable - fields. - - ``Impor*`` to find 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 - 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:`Sequence[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. - # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, - *, - scope: str = None, - query: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (:class:`google.cloud.asset_v1.types.SearchAllIamPoliciesRequest`): - 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 Cloud IAM policy binding, including its - members, roles, and Cloud IAM conditions. The returned - Cloud IAM policies will only contain the bindings that - match your query. To learn more about the IAM policy - structure, see `IAM policy - doc `__. - - 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 "user" member type. - - 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. - # Sanity 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: asset_service.AnalyzeIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: - r"""Analyzes IAM policies to answer which identities have - what accesses on which resources. - - Args: - request (:class:`google.cloud.asset_v1.types.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: - 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: asset_service.AnalyzeIamPolicyLongrunningRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 request - to help callers to map responses to requests. - - Args: - request (:class:`google.cloud.asset_v1.types.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: - 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.AnalyzeIamPolicyLongrunningRequest, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 aa285d83..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/client.py +++ /dev/null @@ -1,1463 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -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.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 - - -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 - - def get_transport_class(cls, - label: 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 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport, None] = None, - client_options: Optional[client_options_lib.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 (google.api_core.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. - 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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: - 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: - 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, - ) - - def export_assets(self, - request: asset_service.ExportAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 proto 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. - - Args: - request (google.cloud.asset_v1.types.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: - 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: asset_service.ListAssetsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - Args: - request (google.cloud.asset_v1.types.ListAssetsRequest): - 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_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. - # Sanity 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: asset_service.BatchGetAssetsHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.asset_v1.types.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: - 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: asset_service.CreateFeedRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Args: - request (google.cloud.asset_v1.types.CreateFeedRequest): - 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. - # Sanity 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: asset_service.GetFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - Args: - request (google.cloud.asset_v1.types.GetFeedRequest): - 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. - # Sanity 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: asset_service.ListFeedsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - Args: - request (google.cloud.asset_v1.types.ListFeedsRequest): - 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. - # Sanity 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: asset_service.UpdateFeedRequest = None, - *, - feed: asset_service.Feed = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - Args: - request (google.cloud.asset_v1.types.UpdateFeedRequest): - 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. - # Sanity 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: asset_service.DeleteFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an asset feed. - - Args: - request (google.cloud.asset_v1.types.DeleteFeedRequest): - 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. - # Sanity 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: asset_service.SearchAllResourcesRequest = None, - *, - scope: str = None, - query: str = None, - asset_types: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesPager: - r"""Searches all 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. - - Args: - request (google.cloud.asset_v1.types.SearchAllResourcesRequest): - 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 Cloud resources whose name - contains "Important" as a word. - - ``name=Important`` to find the Cloud resource whose - name is exactly "Important". - - ``displayName:Impor*`` to find Cloud resources whose - display name contains "Impor" as a prefix of any word - in the field. - - ``location:us-west*`` to find Cloud resources whose - location contains both "us" and "west" as prefixes. - - ``labels:prod`` to find Cloud resources whose labels - contain "prod" as a key or value. - - ``labels.env:prod`` to find Cloud resources that have - a label "env" and its value is "prod". - - ``labels.env:*`` to find Cloud resources that have a - label "env". - - ``kmsKey:key`` to find Cloud resources encrypted with - a customer-managed encryption key whose name contains - the word "key". - - ``state:ACTIVE`` to find Cloud resources whose state - contains "ACTIVE" as a word. - - ``NOT state:ACTIVE`` to find {{gcp_name}} resources - whose state doesn't contain "ACTIVE" as a word. - - ``createTime<1609459200`` to find 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 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 Cloud resources that contain - "Important" as a word in any of the searchable - fields. - - ``Impor*`` to find 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 - 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 (Sequence[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. - # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, - *, - scope: str = None, - query: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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. - - Args: - request (google.cloud.asset_v1.types.SearchAllIamPoliciesRequest): - 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 Cloud IAM policy binding, including its - members, roles, and Cloud IAM conditions. The returned - Cloud IAM policies will only contain the bindings that - match your query. To learn more about the IAM policy - structure, see `IAM policy - doc `__. - - 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 "user" member type. - - 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. - # Sanity 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: asset_service.AnalyzeIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: - r"""Analyzes IAM policies to answer which identities have - what accesses on which resources. - - Args: - request (google.cloud.asset_v1.types.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: - 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: asset_service.AnalyzeIamPolicyLongrunningRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - 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 request - to help callers to map responses to requests. - - Args: - request (google.cloud.asset_v1.types.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: - 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.AnalyzeIamPolicyLongrunningRequest, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 c09af15c..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/pagers.py +++ /dev/null @@ -1,385 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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/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 2c12069f..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', -) 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 f2ec182e..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/base.py +++ /dev/null @@ -1,383 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-asset', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -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: 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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # If the credentials is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - 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, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """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() - - -__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 d20c2b24..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,598 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> 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 applicatin 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 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 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 = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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: ga_credentials.Credentials = None, - credentials_file: 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. - """ - # Sanity 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 proto 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 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 request - to help callers to map responses to requests. - - 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'] - - -__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 0634b4f4..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,602 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -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: 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> 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 applicatin 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 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 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 = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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. - """ - # Sanity 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 proto 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 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 request - to help callers to map responses to requests. - - 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'] - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) 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 f20e2224..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/types/__init__.py +++ /dev/null @@ -1,104 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ( - AnalyzeIamPolicyLongrunningRequest, - AnalyzeIamPolicyLongrunningResponse, - AnalyzeIamPolicyRequest, - AnalyzeIamPolicyResponse, - BatchGetAssetsHistoryRequest, - BatchGetAssetsHistoryResponse, - BigQueryDestination, - CreateFeedRequest, - DeleteFeedRequest, - ExportAssetsRequest, - ExportAssetsResponse, - Feed, - FeedOutputConfig, - GcsDestination, - GcsOutputResult, - GetFeedRequest, - IamPolicyAnalysisOutputConfig, - IamPolicyAnalysisQuery, - ListAssetsRequest, - ListAssetsResponse, - ListFeedsRequest, - ListFeedsResponse, - OutputConfig, - OutputResult, - PartitionSpec, - PubsubDestination, - SearchAllIamPoliciesRequest, - SearchAllIamPoliciesResponse, - SearchAllResourcesRequest, - SearchAllResourcesResponse, - UpdateFeedRequest, - ContentType, -) -from .assets import ( - Asset, - ConditionEvaluation, - IamPolicyAnalysisResult, - IamPolicyAnalysisState, - IamPolicySearchResult, - Resource, - ResourceSearchResult, - TemporalAsset, - TimeWindow, -) - -__all__ = ( - 'AnalyzeIamPolicyLongrunningRequest', - 'AnalyzeIamPolicyLongrunningResponse', - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'BatchGetAssetsHistoryRequest', - 'BatchGetAssetsHistoryResponse', - 'BigQueryDestination', - 'CreateFeedRequest', - 'DeleteFeedRequest', - 'ExportAssetsRequest', - 'ExportAssetsResponse', - 'Feed', - 'FeedOutputConfig', - 'GcsDestination', - 'GcsOutputResult', - 'GetFeedRequest', - 'IamPolicyAnalysisOutputConfig', - 'IamPolicyAnalysisQuery', - 'ListAssetsRequest', - 'ListAssetsResponse', - 'ListFeedsRequest', - 'ListFeedsResponse', - 'OutputConfig', - 'OutputResult', - 'PartitionSpec', - 'PubsubDestination', - 'SearchAllIamPoliciesRequest', - 'SearchAllIamPoliciesResponse', - 'SearchAllResourcesRequest', - 'SearchAllResourcesResponse', - 'UpdateFeedRequest', - 'ContentType', - 'Asset', - 'ConditionEvaluation', - 'IamPolicyAnalysisResult', - 'IamPolicyAnalysisState', - 'IamPolicySearchResult', - 'Resource', - 'ResourceSearchResult', - 'TemporalAsset', - 'TimeWindow', -) 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 8ecee480..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/types/asset_service.py +++ /dev/null @@ -1,1700 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.asset_v1.types import assets as gca_assets -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.type import expr_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1', - manifest={ - 'ContentType', - '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', - }, -) - - -class ContentType(proto.Enum): - r"""Asset content type.""" - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - ORG_POLICY = 4 - ACCESS_POLICY = 5 - OS_INVENTORY = 6 - - -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 (Sequence[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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - output_config = proto.Field( - proto.MESSAGE, - number=5, - message='OutputConfig', - ) - - -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 Google 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 Google Cloud Storage object limit. - """ - - read_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - output_config = proto.Field( - proto.MESSAGE, - number=2, - message='OutputConfig', - ) - output_result = proto.Field( - proto.MESSAGE, - number=3, - message='OutputResult', - ) - - -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 (Sequence[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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - page_size = proto.Field( - proto.INT32, - number=5, - ) - page_token = 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 (Sequence[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 = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - assets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gca_assets.Asset, - ) - next_page_token = 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 (Sequence[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. - """ - - parent = proto.Field( - proto.STRING, - number=1, - ) - asset_names = proto.RepeatedField( - proto.STRING, - number=2, - ) - content_type = proto.Field( - proto.ENUM, - number=3, - enum='ContentType', - ) - read_time_window = proto.Field( - proto.MESSAGE, - number=4, - message=gca_assets.TimeWindow, - ) - - -class BatchGetAssetsHistoryResponse(proto.Message): - r"""Batch get assets history response. - Attributes: - assets (Sequence[google.cloud.asset_v1.types.TemporalAsset]): - A list of assets with valid time windows. - """ - - assets = 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 = proto.Field( - proto.STRING, - number=1, - ) - feed_id = proto.Field( - proto.STRING, - number=2, - ) - 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFeedsResponse(proto.Message): - r""" - Attributes: - feeds (Sequence[google.cloud.asset_v1.types.Feed]): - A list of feeds. - """ - - feeds = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Feed', - ) - update_mask = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class OutputConfig(proto.Message): - r"""Output configuration for export assets destination. - Attributes: - gcs_destination (google.cloud.asset_v1.types.GcsDestination): - Destination on Cloud Storage. - bigquery_destination (google.cloud.asset_v1.types.BigQueryDestination): - Destination on BigQuery. The output table - stores the fields in asset proto as columns in - BigQuery. - """ - - gcs_destination = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - bigquery_destination = proto.Field( - proto.MESSAGE, - number=2, - oneof='destination', - message='BigQueryDestination', - ) - - -class OutputResult(proto.Message): - r"""Output result of export assets. - Attributes: - gcs_result (google.cloud.asset_v1.types.GcsOutputResult): - Export result on Cloud Storage. - """ - - gcs_result = proto.Field( - proto.MESSAGE, - number=1, - oneof='result', - message='GcsOutputResult', - ) - - -class GcsOutputResult(proto.Message): - r"""A Cloud Storage output result. - Attributes: - uris (Sequence[str]): - List of uris of the Cloud Storage objects. Example: - "gs://bucket_name/object_name". - """ - - uris = proto.RepeatedField( - proto.STRING, - number=1, - ) - - -class GcsDestination(proto.Message): - r"""A Cloud Storage location. - 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. - 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. - """ - - uri = proto.Field( - proto.STRING, - number=1, - oneof='object_uri', - ) - uri_prefix = 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. - 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 = proto.Field( - proto.STRING, - number=1, - ) - table = proto.Field( - proto.STRING, - number=2, - ) - force = proto.Field( - proto.BOOL, - number=3, - ) - partition_spec = proto.Field( - proto.MESSAGE, - number=4, - message='PartitionSpec', - ) - separate_tables_per_asset_type = 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). - """ - PARTITION_KEY_UNSPECIFIED = 0 - READ_TIME = 1 - REQUEST_TIME = 2 - - partition_key = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class FeedOutputConfig(proto.Message): - r"""Output configuration for asset feed destination. - Attributes: - pubsub_destination (google.cloud.asset_v1.types.PubsubDestination): - Destination on Pub/Sub. - """ - - pubsub_destination = 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 (Sequence[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``. - See `Resource - Names `__ - for more info. - asset_types (Sequence[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"`` - - See `this - topic `__ - for a list of all 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. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - asset_names = proto.RepeatedField( - proto.STRING, - number=2, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - feed_output_config = proto.Field( - proto.MESSAGE, - number=5, - message='FeedOutputConfig', - ) - condition = proto.Field( - proto.MESSAGE, - number=6, - message=expr_pb2.Expr, - ) - - -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 Cloud resources whose name - contains "Important" as a word. - - ``name=Important`` to find the Cloud resource whose name - is exactly "Important". - - ``displayName:Impor*`` to find Cloud resources whose - display name contains "Impor" as a prefix of any word in - the field. - - ``location:us-west*`` to find Cloud resources whose - location contains both "us" and "west" as prefixes. - - ``labels:prod`` to find Cloud resources whose labels - contain "prod" as a key or value. - - ``labels.env:prod`` to find Cloud resources that have a - label "env" and its value is "prod". - - ``labels.env:*`` to find Cloud resources that have a - label "env". - - ``kmsKey:key`` to find Cloud resources encrypted with a - customer-managed encryption key whose name contains the - word "key". - - ``state:ACTIVE`` to find Cloud resources whose state - contains "ACTIVE" as a word. - - ``NOT state:ACTIVE`` to find {{gcp_name}} resources whose - state doesn't contain "ACTIVE" as a word. - - ``createTime<1609459200`` to find 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 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 Cloud resources that contain - "Important" as a word in any of the searchable fields. - - ``Impor*`` to find 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 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 (Sequence[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, 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 singular primitive - fields in the response are sortable: - - - name - - assetType - - project - - displayName - - description - - location - - kmsKey - - createTime - - updateTime - - state - - parentFullResourceName - - parentAssetType All the other fields such as repeated - fields (e.g., ``networkTags``), map fields (e.g., - ``labels``) and struct fields (e.g., - ``additionalAttributes``) are not supported. - """ - - scope = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - page_token = proto.Field( - proto.STRING, - number=5, - ) - order_by = proto.Field( - proto.STRING, - number=6, - ) - - -class SearchAllResourcesResponse(proto.Message): - r"""Search all resources response. - Attributes: - results (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gca_assets.ResourceSearchResult, - ) - next_page_token = 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 Cloud - IAM policy binding, including its members, roles, and Cloud - IAM conditions. The returned Cloud IAM policies will only - contain the bindings that match your query. To learn more - about the IAM policy structure, see `IAM policy - doc `__. - - 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 "user" member type. - 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. - asset_types (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=5, - ) - order_by = proto.Field( - proto.STRING, - number=7, - ) - - -class SearchAllIamPoliciesResponse(proto.Message): - r"""Search all IAM policies response. - Attributes: - results (Sequence[google.cloud.asset_v1.types.IamPolicySearchResult]): - A list of IamPolicy 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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=gca_assets.IamPolicySearchResult, - ) - next_page_token = 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 = 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 members 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 = 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 (Sequence[str]): - Optional. The roles to appear in result. - permissions (Sequence[str]): - Optional. The permissions to appear in - result. - """ - - roles = proto.RepeatedField( - proto.STRING, - number=1, - ) - permissions = 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. - - 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 GCP 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 resource cannot be used - together with this option. - - For example, if the request analyzes for which users have - permission P on a GCP project with this option enabled, the - results will include all users who have permission P on that - project or any lower resource. - - Default is false. - output_resource_edges (bool): - Optional. If true, the result will output - resource edges, starting from the policy - attached resource, to any expanded resources. - Default is false. - output_group_edges (bool): - Optional. If true, the result will output - group identity edges, starting from the - binding's group members, to any expanded - identities. 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 GCP folder F, then - user A potentially has access to the GCP 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 GCP 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 GCP folder F, - then user A potentially has access to the GCP 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]. - - Default is false. - """ - - expand_groups = proto.Field( - proto.BOOL, - number=1, - ) - expand_roles = proto.Field( - proto.BOOL, - number=2, - ) - expand_resources = proto.Field( - proto.BOOL, - number=3, - ) - output_resource_edges = proto.Field( - proto.BOOL, - number=4, - ) - output_group_edges = proto.Field( - proto.BOOL, - number=5, - ) - analyze_service_account_impersonation = proto.Field( - proto.BOOL, - number=6, - ) - - class ConditionContext(proto.Message): - r"""The IAM conditions context. - 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. - """ - - access_time = proto.Field( - proto.MESSAGE, - number=1, - oneof='TimeContext', - message=timestamp_pb2.Timestamp, - ) - - scope = proto.Field( - proto.STRING, - number=1, - ) - resource_selector = proto.Field( - proto.MESSAGE, - number=2, - message=ResourceSelector, - ) - identity_selector = proto.Field( - proto.MESSAGE, - number=3, - message=IdentitySelector, - ) - access_selector = proto.Field( - proto.MESSAGE, - number=4, - message=AccessSelector, - ) - options = proto.Field( - proto.MESSAGE, - number=5, - message=Options, - ) - condition_context = 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. - 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 = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - execution_timeout = 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 (Sequence[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 (Sequence[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 (Sequence[google.cloud.asset_v1.types.IamPolicyAnalysisState]): - A list of non-critical errors happened during - the query handling. - """ - - analysis_query = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - analysis_results = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gca_assets.IamPolicyAnalysisResult, - ) - fully_explored = proto.Field( - proto.BOOL, - number=3, - ) - non_critical_errors = proto.RepeatedField( - proto.MESSAGE, - number=5, - message=gca_assets.IamPolicyAnalysisState, - ) - - main_analysis = proto.Field( - proto.MESSAGE, - number=1, - message=IamPolicyAnalysis, - ) - service_account_impersonation_analysis = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=IamPolicyAnalysis, - ) - fully_explored = proto.Field( - proto.BOOL, - number=3, - ) - - -class IamPolicyAnalysisOutputConfig(proto.Message): - r"""Output configuration for export IAM policy analysis - destination. - - Attributes: - gcs_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.GcsDestination): - Destination on Cloud Storage. - bigquery_destination (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig.BigQueryDestination): - Destination on BigQuery. - """ - - 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 = 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. - """ - PARTITION_KEY_UNSPECIFIED = 0 - REQUEST_TIME = 1 - - dataset = proto.Field( - proto.STRING, - number=1, - ) - table_prefix = proto.Field( - proto.STRING, - number=2, - ) - partition_key = proto.Field( - proto.ENUM, - number=3, - enum='IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey', - ) - write_disposition = proto.Field( - proto.STRING, - number=4, - ) - - gcs_destination = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message=GcsDestination, - ) - bigquery_destination = 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. - output_config (google.cloud.asset_v1.types.IamPolicyAnalysisOutputConfig): - Required. Output configuration indicating - where the results will be output to. - """ - - analysis_query = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - output_config = 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]. - """ - - -__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 b2b5a915..00000000 --- a/owl-bot-staging/v1/google/cloud/asset_v1/types/assets.py +++ /dev/null @@ -1,1084 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore -from google.cloud.osconfig.v1 import inventory_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 -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', - 'ResourceSearchResult', - '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.""" - PRIOR_ASSET_STATE_UNSPECIFIED = 0 - PRESENT = 1 - INVALID = 2 - DOES_NOT_EXIST = 3 - DELETED = 4 - - window = proto.Field( - proto.MESSAGE, - number=1, - message='TimeWindow', - ) - deleted = proto.Field( - proto.BOOL, - number=2, - ) - asset = proto.Field( - proto.MESSAGE, - number=3, - message='Asset', - ) - prior_asset_state = proto.Field( - proto.ENUM, - number=4, - enum=PriorAssetState, - ) - prior_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 = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = 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. - Cloud IAM policy), or a relationship (e.g. an - INSTANCE_TO_INSTANCEGROUP relationship). See `Supported asset - types `__ - for more information. - - 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 Cloud IAM policy set on a Google - Cloud resource. There can be a maximum of one Cloud IAM - policy set on any given resource. In addition, Cloud 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 (Sequence[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 `__. - access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): - Please also refer to the `access level user - guide `__. - service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): - Please also refer to the `service perimeter user - guide `__. - os_inventory (google.cloud.osconfig.v1.inventory_pb2.Inventory): - A representation of runtime OS Inventory information. See - `this - topic `__ - for more information. - ancestors (Sequence[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 = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - name = proto.Field( - proto.STRING, - number=1, - ) - asset_type = proto.Field( - proto.STRING, - number=2, - ) - resource = proto.Field( - proto.MESSAGE, - number=3, - message='Resource', - ) - iam_policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - org_policy = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=orgpolicy_pb2.Policy, - ) - access_policy = proto.Field( - proto.MESSAGE, - number=7, - oneof='access_context_policy', - message=access_policy_pb2.AccessPolicy, - ) - access_level = proto.Field( - proto.MESSAGE, - number=8, - oneof='access_context_policy', - message=access_level_pb2.AccessLevel, - ) - service_perimeter = proto.Field( - proto.MESSAGE, - number=9, - oneof='access_context_policy', - message=service_perimeter_pb2.ServicePerimeter, - ) - os_inventory = proto.Field( - proto.MESSAGE, - number=12, - message=inventory_pb2.Inventory, - ) - ancestors = 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 `Cloud 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 = proto.Field( - proto.STRING, - number=1, - ) - discovery_document_uri = proto.Field( - proto.STRING, - number=2, - ) - discovery_name = proto.Field( - proto.STRING, - number=3, - ) - resource_url = proto.Field( - proto.STRING, - number=4, - ) - parent = proto.Field( - proto.STRING, - number=5, - ) - data = proto.Field( - proto.MESSAGE, - number=6, - message=struct_pb2.Struct, - ) - location = proto.Field( - proto.STRING, - number=8, - ) - - -class ResourceSearchResult(proto.Message): - r"""A result of Resource Search, containing information of a - cloud resource. - - 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 (Sequence[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 proto 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 proto 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 proto contains it. - - To search against the ``location``: - - - use a field query. Example: ``location:us-west*`` - - use a free text query. Example: ``us-west*`` - labels (Sequence[google.cloud.asset_v1.types.ResourceSearchResult.LabelsEntry]): - Labels associated with this resource. See `Labelling and - grouping GCP - resources `__ - for more information. This field is available only when the - resource's proto 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 (Sequence[str]): - Network tags associated with this resource. Like labels, - network tags are a type of annotations used to group GCP - resources. See `Labelling GCP - resources `__ - for more information. This field is available only when the - resource's proto 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 is available only when the resource's proto - contains it. - - To search against the ``kms_key``: - - - use a field query. Example: ``kmsKey: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 proto 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 proto 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 proto 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 Cloud 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 GCP 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 GCP 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`` - 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`` - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - asset_type = proto.Field( - proto.STRING, - number=2, - ) - project = proto.Field( - proto.STRING, - number=3, - ) - folders = proto.RepeatedField( - proto.STRING, - number=17, - ) - organization = proto.Field( - proto.STRING, - number=18, - ) - display_name = proto.Field( - proto.STRING, - number=4, - ) - description = proto.Field( - proto.STRING, - number=5, - ) - location = proto.Field( - proto.STRING, - number=6, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=7, - ) - network_tags = proto.RepeatedField( - proto.STRING, - number=8, - ) - kms_key = proto.Field( - proto.STRING, - number=10, - ) - create_time = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - update_time = proto.Field( - proto.MESSAGE, - number=12, - message=timestamp_pb2.Timestamp, - ) - state = proto.Field( - proto.STRING, - number=13, - ) - additional_attributes = proto.Field( - proto.MESSAGE, - number=9, - message=struct_pb2.Struct, - ) - parent_full_resource_name = proto.Field( - proto.STRING, - number=19, - ) - parent_asset_type = proto.Field( - proto.STRING, - number=103, - ) - - -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 GCP 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 (Sequence[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 (Sequence[google.cloud.asset_v1.types.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): - 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 (Sequence[str]): - A list of permissions. A sample permission string: - ``compute.disk.get``. - """ - - permissions = proto.RepeatedField( - proto.STRING, - number=1, - ) - - matched_permissions = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='IamPolicySearchResult.Explanation.Permissions', - ) - - resource = proto.Field( - proto.STRING, - number=1, - ) - asset_type = proto.Field( - proto.STRING, - number=5, - ) - project = proto.Field( - proto.STRING, - number=2, - ) - folders = proto.RepeatedField( - proto.STRING, - number=6, - ) - organization = proto.Field( - proto.STRING, - number=7, - ) - policy = proto.Field( - proto.MESSAGE, - number=3, - message=policy_pb2.Policy, - ) - 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 = proto.Field( - proto.ENUM, - number=1, - enum=code_pb2.Code, - ) - cause = 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.""" - EVALUATION_VALUE_UNSPECIFIED = 0 - TRUE = 1 - FALSE = 2 - CONDITIONAL = 3 - - evaluation_value = 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 Cloud IAM policy binding under analysis. - access_control_lists (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - analysis_state = proto.Field( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisState', - ) - - class Access(proto.Message): - r"""An IAM role or permission under analysis. - Attributes: - role (str): - The role. - permission (str): - The permission. - analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): - The analysis state of this access. - """ - - role = proto.Field( - proto.STRING, - number=1, - oneof='oneof_access', - ) - permission = proto.Field( - proto.STRING, - number=2, - oneof='oneof_access', - ) - analysis_state = proto.Field( - proto.MESSAGE, - number=3, - message='IamPolicyAnalysisState', - ) - - class Identity(proto.Message): - r"""An identity under analysis. - Attributes: - name (str): - The identity name in any form of members appear in `IAM - policy - binding `__, - such as: - - - user:foo@google.com - - group:group1@google.com - - serviceAccount:s1@prj1.iam.gserviceaccount.com - - projectOwner:some_project_id - - domain:google.com - - allUsers - - etc. - analysis_state (google.cloud.asset_v1.types.IamPolicyAnalysisState): - The analysis state of this identity. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - analysis_state = 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 = proto.Field( - proto.STRING, - number=1, - ) - target_node = 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 (Sequence[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 (Sequence[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 (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisResult.Resource', - ) - accesses = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.Access', - ) - resource_edges = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='IamPolicyAnalysisResult.Edge', - ) - condition_evaluation = proto.Field( - proto.MESSAGE, - number=4, - message='ConditionEvaluation', - ) - - class IdentityList(proto.Message): - r"""The identities and group edges. - Attributes: - identities (Sequence[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 (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisResult.Identity', - ) - group_edges = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.Edge', - ) - - attached_resource_full_name = proto.Field( - proto.STRING, - number=1, - ) - iam_binding = proto.Field( - proto.MESSAGE, - number=2, - message=policy_pb2.Binding, - ) - access_control_lists = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AccessControlList, - ) - identity_list = proto.Field( - proto.MESSAGE, - number=4, - message=IdentityList, - ) - fully_explored = 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 4505b485..00000000 --- a/owl-bot-staging/v1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1/noxfile.py b/owl-bot-staging/v1/noxfile.py deleted file mode 100644 index 15e45490..00000000 --- a/owl-bot-staging/v1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/asset_v1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - 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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) 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 4a9e79e9..00000000 --- a/owl-bot-staging/v1/scripts/fixup_asset_v1_keywords.py +++ /dev/null @@ -1,187 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', 'execution_timeout', ), - 'analyze_iam_policy_longrunning': ('analysis_query', 'output_config', ), - 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', ), - 'create_feed': ('parent', 'feed_id', 'feed', ), - 'delete_feed': ('name', ), - 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', ), - 'get_feed': ('name', ), - 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), - 'list_feeds': ('parent', ), - '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', ), - '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: not a.keyword.value 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 1aece31b..00000000 --- a/owl-bot-staging/v1/setup.py +++ /dev/null @@ -1,53 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-asset', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1/tests/__init__.py b/owl-bot-staging/v1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 5d5e291d..00000000 --- a/owl-bot-staging/v1/tests/unit/gapic/asset_v1/test_asset_service.py +++ /dev/null @@ -1,4046 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -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_async # type: ignore -from google.api_core import operations_v1 -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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.asset_v1.types import asset_service -from google.cloud.asset_v1.types import assets -from google.longrunning import operations_pb2 -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.type import expr_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - ] - 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"), -]) -@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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@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"), -]) -@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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -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, - ) - - -def test_export_assets(transport: str = 'grpc', request_type=asset_service.ExportAssetsRequest): - 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_from_dict(): - test_export_assets(request_type=dict) - - -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'] - - -def test_list_assets(transport: str = 'grpc', request_type=asset_service.ListAssetsRequest): - 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_from_dict(): - test_list_assets(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, assets.Asset) - for i in results) - -def test_list_assets_pages(): - 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: - # 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: - 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 = [] - async for page_ in (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 - -def test_batch_get_assets_history(transport: str = 'grpc', request_type=asset_service.BatchGetAssetsHistoryRequest): - 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_from_dict(): - test_batch_get_assets_history(request_type=dict) - - -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'] - - -def test_create_feed(transport: str = 'grpc', request_type=asset_service.CreateFeedRequest): - 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_from_dict(): - test_create_feed(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_get_feed(transport: str = 'grpc', request_type=asset_service.GetFeedRequest): - 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_from_dict(): - test_get_feed(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_list_feeds(transport: str = 'grpc', request_type=asset_service.ListFeedsRequest): - 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_from_dict(): - test_list_feeds(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_update_feed(transport: str = 'grpc', request_type=asset_service.UpdateFeedRequest): - 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_from_dict(): - test_update_feed(request_type=dict) - - -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 = 'feed.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=feed.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 = 'feed.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=feed.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] - assert args[0].feed == asset_service.Feed(name='name_value') - - -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] - assert args[0].feed == asset_service.Feed(name='name_value') - - -@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'), - ) - - -def test_delete_feed(transport: str = 'grpc', request_type=asset_service.DeleteFeedRequest): - 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_from_dict(): - test_delete_feed(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_search_all_resources(transport: str = 'grpc', request_type=asset_service.SearchAllResourcesRequest): - 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_from_dict(): - test_search_all_resources(request_type=dict) - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - assert args[0].asset_types == ['asset_types_value'] - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - assert args[0].asset_types == ['asset_types_value'] - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, assets.ResourceSearchResult) - for i in results) - -def test_search_all_resources_pages(): - 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: - # 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: - 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 = [] - async for page_ in (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 - -def test_search_all_iam_policies(transport: str = 'grpc', request_type=asset_service.SearchAllIamPoliciesRequest): - 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_from_dict(): - test_search_all_iam_policies(request_type=dict) - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, assets.IamPolicySearchResult) - for i in results) - -def test_search_all_iam_policies_pages(): - 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: - # 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: - 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 = [] - async for page_ in (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 - -def test_analyze_iam_policy(transport: str = 'grpc', request_type=asset_service.AnalyzeIamPolicyRequest): - 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_from_dict(): - test_analyze_iam_policy(request_type=dict) - - -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 = 'analysis_query.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=analysis_query.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 = 'analysis_query.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=analysis_query.scope/value', - ) in kw['metadata'] - - -def test_analyze_iam_policy_longrunning(transport: str = 'grpc', request_type=asset_service.AnalyzeIamPolicyLongrunningRequest): - 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_from_dict(): - test_analyze_iam_policy_longrunning(request_type=dict) - - -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 = 'analysis_query.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=analysis_query.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 = 'analysis_query.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=analysis_query.scope/value', - ) in kw['metadata'] - - -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 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, -]) -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() - -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', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_base_transport_with_credentials_file_old_google_auth(): - # 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=( - '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() - - -@requires_google_auth_gte_1_25_0 -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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_auth_adc_old_google_auth(): - # 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=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -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, - ], -) -@requires_google_auth_lt_1_25_0 -def test_asset_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@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_host_no_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_host_with_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:8000' - -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_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 = "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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p1beta1/.coveragerc b/owl-bot-staging/v1p1beta1/.coveragerc deleted file mode 100644 index 3425850c..00000000 --- a/owl-bot-staging/v1p1beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound 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/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 d0875802..00000000 --- a/owl-bot-staging/v1p1beta1/docs/asset_v1p1beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Asset v1p1beta1 API -========================================== - -.. automodule:: google.cloud.asset_v1p1beta1.types - :members: - :undoc-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 3aa26721..00000000 --- a/owl-bot-staging/v1p1beta1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-asset" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-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 = [ - ( - master_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 = [ - ( - master_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 = [ - ( - master_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 7f1c3781..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,37 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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/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 7f5126b4..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/__init__.py +++ /dev/null @@ -1,38 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .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 175cd294..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/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_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" - ] - } - } - } - } - } - } -} 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 4de65971..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 357f9520..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 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 58f4c63c..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,403 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # 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 .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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: 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: asset_service.SearchAllResourcesRequest = None, - *, - scope: str = None, - query: str = None, - asset_types: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesAsyncPager: - r"""Searches all the resources under a given accessible - CRM scope (project/folder/organization). This RPC gives - callers especially admins the ability to search all the - resources under 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 it will be rejected. - - Args: - request (:class:`google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest`): - 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:`Sequence[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. - # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, - *, - scope: str = None, - query: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllIamPoliciesAsyncPager: - r"""Searches all the IAM policies under a given - accessible CRM scope (project/folder/organization). This - RPC gives callers especially admins the ability to - search all the IAM policies under 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 it will be rejected. - - Args: - request (:class:`google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest`): - 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. - # Sanity 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 5e6c3745..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/client.py +++ /dev/null @@ -1,567 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -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 .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport, None] = None, - client_options: Optional[client_options_lib.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 (google.api_core.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. - 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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: - 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: - 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, - ) - - def search_all_resources(self, - request: asset_service.SearchAllResourcesRequest = None, - *, - scope: str = None, - query: str = None, - asset_types: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllResourcesPager: - r"""Searches all the resources under a given accessible - CRM scope (project/folder/organization). This RPC gives - callers especially admins the ability to search all the - resources under 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 it will be rejected. - - Args: - request (google.cloud.asset_v1p1beta1.types.SearchAllResourcesRequest): - 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 (Sequence[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. - # Sanity 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: asset_service.SearchAllIamPoliciesRequest = None, - *, - scope: str = None, - query: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchAllIamPoliciesPager: - r"""Searches all the IAM policies under a given - accessible CRM scope (project/folder/organization). This - RPC gives callers especially admins the ability to - search all the IAM policies under 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 it will be rejected. - - Args: - request (google.cloud.asset_v1p1beta1.types.SearchAllIamPoliciesRequest): - 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. - # Sanity 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 c8df82b2..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py +++ /dev/null @@ -1,263 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 2c12069f..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', -) 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 2b949ef9..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,196 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-asset', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -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: 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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # If the credentials is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - 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, - ), - } - - @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() - - -__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 c906b681..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,291 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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 .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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> 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 applicatin 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 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 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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: ga_credentials.Credentials = None, - credentials_file: 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 under a given accessible - CRM scope (project/folder/organization). This RPC gives - callers especially admins the ability to search all the - resources under 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 it 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 under a given - accessible CRM scope (project/folder/organization). This - RPC gives callers especially admins the ability to - search all the IAM policies under 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 it 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'] - - -__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 e04b788e..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,295 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.asset_v1p1beta1.types import asset_service -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: 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> 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 applicatin 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 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 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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 under a given accessible - CRM scope (project/folder/organization). This RPC gives - callers especially admins the ability to search all the - resources under 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 it 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 under a given - accessible CRM scope (project/folder/organization). This - RPC gives callers especially admins the ability to - search all the IAM policies under 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 it 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'] - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) 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 c7f5d9a4..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/__init__.py +++ /dev/null @@ -1,36 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 2216599b..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/asset_service.py +++ /dev/null @@ -1,205 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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 (Sequence[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, " foo , bar desc ". - """ - - scope = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=3, - ) - page_size = proto.Field( - proto.INT32, - number=4, - ) - page_token = proto.Field( - proto.STRING, - number=5, - ) - order_by = proto.Field( - proto.STRING, - number=10, - ) - - -class SearchAllResourcesResponse(proto.Message): - r"""Search all resources response. - Attributes: - results (Sequence[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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=assets.StandardResourceMetadata, - ) - next_page_token = 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 = proto.Field( - proto.STRING, - number=1, - ) - query = proto.Field( - proto.STRING, - number=2, - ) - page_size = proto.Field( - proto.INT32, - number=3, - ) - page_token = proto.Field( - proto.STRING, - number=4, - ) - - -class SearchAllIamPoliciesResponse(proto.Message): - r"""Search all IAM policies response. - Attributes: - results (Sequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult]): - A list of IamPolicy 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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=assets.IamPolicySearchResult, - ) - next_page_token = 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 a351622a..00000000 --- a/owl-bot-staging/v1p1beta1/google/cloud/asset_v1p1beta1/types/assets.py +++ /dev/null @@ -1,193 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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 (Sequence[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- - ast1", or zonal like "us-west1-b". - labels (Sequence[google.cloud.asset_v1p1beta1.types.StandardResourceMetadata.LabelsEntry]): - Labels associated with this resource. See `Labelling and - grouping GCP - resources `__ - for more information. - network_tags (Sequence[str]): - Network tags associated with this resource. Like labels, - network tags are a type of annotations used to group GCP - resources. See `Labelling GCP - resources `__ - for more information. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - asset_type = proto.Field( - proto.STRING, - number=2, - ) - project = proto.Field( - proto.STRING, - number=3, - ) - display_name = proto.Field( - proto.STRING, - number=4, - ) - description = proto.Field( - proto.STRING, - number=5, - ) - additional_attributes = proto.RepeatedField( - proto.STRING, - number=10, - ) - location = proto.Field( - proto.STRING, - number=11, - ) - labels = proto.MapField( - proto.STRING, - proto.STRING, - number=12, - ) - network_tags = proto.RepeatedField( - proto.STRING, - number=13, - ) - - -class IamPolicySearchResult(proto.Message): - r"""The result for a 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 GCP 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, the project field will be empty. - 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. - explanation (google.cloud.asset_v1p1beta1.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 (Sequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): - The map from roles to their included permission matching the - permission query (e.g. containing - ``policy.role.permissions:``). A sample 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 = proto.MapField( - proto.STRING, - proto.MESSAGE, - number=1, - message='Permissions', - ) - - resource = proto.Field( - proto.STRING, - number=1, - ) - project = proto.Field( - proto.STRING, - number=3, - ) - policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - explanation = proto.Field( - proto.MESSAGE, - number=5, - message=Explanation, - ) - - -class Permissions(proto.Message): - r"""IAM permissions - Attributes: - permissions (Sequence[str]): - A list of permissions. A sample permission - string: "compute.disk.get". - """ - - permissions = 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 4505b485..00000000 --- a/owl-bot-staging/v1p1beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p1beta1/noxfile.py b/owl-bot-staging/v1p1beta1/noxfile.py deleted file mode 100644 index 0c3db615..00000000 --- a/owl-bot-staging/v1p1beta1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/asset_v1p1beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - 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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) 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 dc77c201..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 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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: not a.keyword.value 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 1aece31b..00000000 --- a/owl-bot-staging/v1p1beta1/setup.py +++ /dev/null @@ -1,53 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-asset', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1p1beta1/tests/__init__.py b/owl-bot-staging/v1p1beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 883e9d6d..00000000 --- a/owl-bot-staging/v1p1beta1/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py +++ /dev/null @@ -1,1766 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -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.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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.asset_v1p1beta1.types import asset_service -from google.cloud.asset_v1p1beta1.types import assets -from google.oauth2 import service_account -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - ] - 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"), -]) -@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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@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"), -]) -@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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -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, - ) - - -def test_search_all_resources(transport: str = 'grpc', request_type=asset_service.SearchAllResourcesRequest): - 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_from_dict(): - test_search_all_resources(request_type=dict) - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - assert args[0].asset_types == ['asset_types_value'] - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - assert args[0].asset_types == ['asset_types_value'] - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, assets.StandardResourceMetadata) - for i in results) - -def test_search_all_resources_pages(): - 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: - # 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: - 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 = [] - async for page_ in (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 - -def test_search_all_iam_policies(transport: str = 'grpc', request_type=asset_service.SearchAllIamPoliciesRequest): - 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_from_dict(): - test_search_all_iam_policies(request_type=dict) - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - - -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] - assert args[0].scope == 'scope_value' - assert args[0].query == 'query_value' - - -@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(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, assets.IamPolicySearchResult) - for i in results) - -def test_search_all_iam_policies_pages(): - 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: - # 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: - 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 = [] - async for page_ in (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 - - -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 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, -]) -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() - -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()) - - -@requires_google_auth_gte_1_25_0 -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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_base_transport_with_credentials_file_old_google_auth(): - # 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=( - '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() - - -@requires_google_auth_gte_1_25_0 -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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_auth_adc_old_google_auth(): - # 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=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -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, - ], -) -@requires_google_auth_lt_1_25_0 -def test_asset_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@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_host_no_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_host_with_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:8000' - -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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p2beta1/.coveragerc b/owl-bot-staging/v1p2beta1/.coveragerc deleted file mode 100644 index 3425850c..00000000 --- a/owl-bot-staging/v1p2beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound 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/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 b83adc35..00000000 --- a/owl-bot-staging/v1p2beta1/docs/asset_v1p2beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Asset v1p2beta1 API -========================================== - -.. automodule:: google.cloud.asset_v1p2beta1.types - :members: - :undoc-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 3aa26721..00000000 --- a/owl-bot-staging/v1p2beta1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-asset" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-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 = [ - ( - master_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 = [ - ( - master_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 = [ - ( - master_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 d7ceebac..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,55 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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/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 6395a04b..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/__init__.py +++ /dev/null @@ -1,56 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .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 3c3674a8..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/gapic_metadata.json +++ /dev/null @@ -1,73 +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" - ] - } - } - } - } - } - } -} 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 4de65971..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 357f9520..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 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 517d56f6..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,578 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 .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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: 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: asset_service.CreateFeedRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Args: - request (:class:`google.cloud.asset_v1p2beta1.types.CreateFeedRequest`): - 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. - # Sanity 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: asset_service.GetFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - Args: - request (:class:`google.cloud.asset_v1p2beta1.types.GetFeedRequest`): - 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. - # Sanity 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: asset_service.ListFeedsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - Args: - request (:class:`google.cloud.asset_v1p2beta1.types.ListFeedsRequest`): - 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. - # Sanity 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: asset_service.UpdateFeedRequest = None, - *, - feed: asset_service.Feed = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - Args: - request (:class:`google.cloud.asset_v1p2beta1.types.UpdateFeedRequest`): - 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. - # Sanity 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: asset_service.DeleteFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an asset feed. - - Args: - request (:class:`google.cloud.asset_v1p2beta1.types.DeleteFeedRequest`): - 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. - # Sanity 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 fbcbbad8..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/client.py +++ /dev/null @@ -1,744 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -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 - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport, None] = None, - client_options: Optional[client_options_lib.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 (google.api_core.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. - 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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: - 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: - 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, - ) - - def create_feed(self, - request: asset_service.CreateFeedRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Creates a feed in a parent - project/folder/organization to listen to its asset - updates. - - Args: - request (google.cloud.asset_v1p2beta1.types.CreateFeedRequest): - 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. - # Sanity 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: asset_service.GetFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Gets details about an asset feed. - - Args: - request (google.cloud.asset_v1p2beta1.types.GetFeedRequest): - 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. - # Sanity 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: asset_service.ListFeedsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.ListFeedsResponse: - r"""Lists all asset feeds in a parent - project/folder/organization. - - Args: - request (google.cloud.asset_v1p2beta1.types.ListFeedsRequest): - 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. - # Sanity 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: asset_service.UpdateFeedRequest = None, - *, - feed: asset_service.Feed = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.Feed: - r"""Updates an asset feed configuration. - - Args: - request (google.cloud.asset_v1p2beta1.types.UpdateFeedRequest): - 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. - # Sanity 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: asset_service.DeleteFeedRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes an asset feed. - - Args: - request (google.cloud.asset_v1p2beta1.types.DeleteFeedRequest): - 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. - # Sanity 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, - ) - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 2c12069f..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', -) 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 4c996833..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,246 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-asset', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -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: 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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # If the credentials is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - 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, - ), - } - - @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() - - -__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 e81ab2e3..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,360 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> 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 applicatin 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 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 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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: ga_credentials.Credentials = None, - credentials_file: 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'] - - -__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 ed18d544..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,364 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -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: 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> 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 applicatin 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 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 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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'] - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) 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 e4c38794..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/__init__.py +++ /dev/null @@ -1,54 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 8a7fa6c7..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/asset_service.py +++ /dev/null @@ -1,310 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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.""" - 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 = proto.Field( - proto.STRING, - number=1, - ) - feed_id = proto.Field( - proto.STRING, - number=2, - ) - 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 = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class ListFeedsResponse(proto.Message): - r""" - Attributes: - feeds (Sequence[google.cloud.asset_v1p2beta1.types.Feed]): - A list of feeds. - """ - - feeds = 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 = proto.Field( - proto.MESSAGE, - number=1, - message='Feed', - ) - update_mask = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class OutputConfig(proto.Message): - r"""Output configuration for export assets destination. - Attributes: - gcs_destination (google.cloud.asset_v1p2beta1.types.GcsDestination): - Destination on Cloud Storage. - """ - - gcs_destination = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message='GcsDestination', - ) - - -class GcsDestination(proto.Message): - r"""A Cloud Storage location. - 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. - """ - - uri = 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 = proto.Field( - proto.STRING, - number=1, - ) - - -class FeedOutputConfig(proto.Message): - r"""Output configuration for asset feed destination. - Attributes: - pubsub_destination (google.cloud.asset_v1p2beta1.types.PubsubDestination): - Destination on Cloud Pubsub. - """ - - pubsub_destination = 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 (Sequence[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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - asset_names = proto.RepeatedField( - proto.STRING, - number=2, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - feed_output_config = 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 766824af..00000000 --- a/owl-bot-staging/v1p2beta1/google/cloud/asset_v1p2beta1/types/assets.py +++ /dev/null @@ -1,212 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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 = proto.Field( - proto.MESSAGE, - number=1, - message='TimeWindow', - ) - deleted = proto.Field( - proto.BOOL, - number=2, - ) - 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 = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - end_time = 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 (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - asset_type = proto.Field( - proto.STRING, - number=2, - ) - resource = proto.Field( - proto.MESSAGE, - number=3, - message='Resource', - ) - iam_policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - ancestors = 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 = proto.Field( - proto.STRING, - number=1, - ) - discovery_document_uri = proto.Field( - proto.STRING, - number=2, - ) - discovery_name = proto.Field( - proto.STRING, - number=3, - ) - resource_url = proto.Field( - proto.STRING, - number=4, - ) - parent = proto.Field( - proto.STRING, - number=5, - ) - data = 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 4505b485..00000000 --- a/owl-bot-staging/v1p2beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p2beta1/noxfile.py b/owl-bot-staging/v1p2beta1/noxfile.py deleted file mode 100644 index bde1730c..00000000 --- a/owl-bot-staging/v1p2beta1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/asset_v1p2beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - 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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) 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 cb36113c..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 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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: not a.keyword.value 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 1aece31b..00000000 --- a/owl-bot-staging/v1p2beta1/setup.py +++ /dev/null @@ -1,53 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-asset', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1p2beta1/tests/__init__.py b/owl-bot-staging/v1p2beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 6e097b89..00000000 --- a/owl-bot-staging/v1p2beta1/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py +++ /dev/null @@ -1,2115 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -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.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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION -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 - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - ] - 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"), -]) -@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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@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"), -]) -@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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -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, - ) - - -def test_create_feed(transport: str = 'grpc', request_type=asset_service.CreateFeedRequest): - 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_from_dict(): - test_create_feed(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_get_feed(transport: str = 'grpc', request_type=asset_service.GetFeedRequest): - 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_from_dict(): - test_get_feed(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -def test_list_feeds(transport: str = 'grpc', request_type=asset_service.ListFeedsRequest): - 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_from_dict(): - test_list_feeds(request_type=dict) - - -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] - assert args[0].parent == 'parent_value' - - -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] - assert args[0].parent == 'parent_value' - - -@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', - ) - - -def test_update_feed(transport: str = 'grpc', request_type=asset_service.UpdateFeedRequest): - 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_from_dict(): - test_update_feed(request_type=dict) - - -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 = 'feed.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=feed.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 = 'feed.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=feed.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] - assert args[0].feed == asset_service.Feed(name='name_value') - - -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] - assert args[0].feed == asset_service.Feed(name='name_value') - - -@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'), - ) - - -def test_delete_feed(transport: str = 'grpc', request_type=asset_service.DeleteFeedRequest): - 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_from_dict(): - test_delete_feed(request_type=dict) - - -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] - assert args[0].name == 'name_value' - - -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] - assert args[0].name == 'name_value' - - -@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', - ) - - -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 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, -]) -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() - -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()) - - -@requires_google_auth_gte_1_25_0 -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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_base_transport_with_credentials_file_old_google_auth(): - # 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=( - '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() - - -@requires_google_auth_gte_1_25_0 -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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_auth_adc_old_google_auth(): - # 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=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -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, - ], -) -@requires_google_auth_lt_1_25_0 -def test_asset_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@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_host_no_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_host_with_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:8000' - -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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p4beta1/.coveragerc b/owl-bot-staging/v1p4beta1/.coveragerc deleted file mode 100644 index 3425850c..00000000 --- a/owl-bot-staging/v1p4beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/owl-bot-staging/v1p4beta1/MANIFEST.in b/owl-bot-staging/v1p4beta1/MANIFEST.in deleted file mode 100644 index 128f583b..00000000 --- a/owl-bot-staging/v1p4beta1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/asset *.py -recursive-include google/cloud/asset_v1p4beta1 *.py diff --git a/owl-bot-staging/v1p4beta1/README.rst b/owl-bot-staging/v1p4beta1/README.rst deleted file mode 100644 index 110d4086..00000000 --- a/owl-bot-staging/v1p4beta1/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/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst deleted file mode 100644 index e46e3c5e..00000000 --- a/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/asset_service.rst +++ /dev/null @@ -1,6 +0,0 @@ -AssetService ------------------------------- - -.. automodule:: google.cloud.asset_v1p4beta1.services.asset_service - :members: - :inherited-members: diff --git a/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst deleted file mode 100644 index 6116177f..00000000 --- a/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Asset v1p4beta1 API -============================================= -.. toctree:: - :maxdepth: 2 - - asset_service diff --git a/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst b/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst deleted file mode 100644 index 60ea41e5..00000000 --- a/owl-bot-staging/v1p4beta1/docs/asset_v1p4beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Asset v1p4beta1 API -========================================== - -.. automodule:: google.cloud.asset_v1p4beta1.types - :members: - :undoc-members: - :show-inheritance: diff --git a/owl-bot-staging/v1p4beta1/docs/conf.py b/owl-bot-staging/v1p4beta1/docs/conf.py deleted file mode 100644 index 3aa26721..00000000 --- a/owl-bot-staging/v1p4beta1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-asset" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-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 = [ - ( - master_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 = [ - ( - master_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 = [ - ( - master_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/v1p4beta1/docs/index.rst b/owl-bot-staging/v1p4beta1/docs/index.rst deleted file mode 100644 index d944a266..00000000 --- a/owl-bot-staging/v1p4beta1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - asset_v1p4beta1/services - asset_v1p4beta1/types diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py deleted file mode 100644 index 4f1ec674..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset/__init__.py +++ /dev/null @@ -1,37 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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_v1p4beta1.services.asset_service.client import AssetServiceClient -from google.cloud.asset_v1p4beta1.services.asset_service.async_client import AssetServiceAsyncClient - -from google.cloud.asset_v1p4beta1.types.asset_service import AnalyzeIamPolicyRequest -from google.cloud.asset_v1p4beta1.types.asset_service import AnalyzeIamPolicyResponse -from google.cloud.asset_v1p4beta1.types.asset_service import ExportIamPolicyAnalysisRequest -from google.cloud.asset_v1p4beta1.types.asset_service import ExportIamPolicyAnalysisResponse -from google.cloud.asset_v1p4beta1.types.asset_service import IamPolicyAnalysisOutputConfig -from google.cloud.asset_v1p4beta1.types.asset_service import IamPolicyAnalysisQuery -from google.cloud.asset_v1p4beta1.types.assets import IamPolicyAnalysisResult - -__all__ = ('AssetServiceClient', - 'AssetServiceAsyncClient', - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'ExportIamPolicyAnalysisRequest', - 'ExportIamPolicyAnalysisResponse', - 'IamPolicyAnalysisOutputConfig', - 'IamPolicyAnalysisQuery', - 'IamPolicyAnalysisResult', -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset/py.typed b/owl-bot-staging/v1p4beta1/google/cloud/asset/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p4beta1/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/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py deleted file mode 100644 index a36f107c..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/__init__.py +++ /dev/null @@ -1,38 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .services.asset_service import AssetServiceClient -from .services.asset_service import AssetServiceAsyncClient - -from .types.asset_service import AnalyzeIamPolicyRequest -from .types.asset_service import AnalyzeIamPolicyResponse -from .types.asset_service import ExportIamPolicyAnalysisRequest -from .types.asset_service import ExportIamPolicyAnalysisResponse -from .types.asset_service import IamPolicyAnalysisOutputConfig -from .types.asset_service import IamPolicyAnalysisQuery -from .types.assets import IamPolicyAnalysisResult - -__all__ = ( - 'AssetServiceAsyncClient', -'AnalyzeIamPolicyRequest', -'AnalyzeIamPolicyResponse', -'AssetServiceClient', -'ExportIamPolicyAnalysisRequest', -'ExportIamPolicyAnalysisResponse', -'IamPolicyAnalysisOutputConfig', -'IamPolicyAnalysisQuery', -'IamPolicyAnalysisResult', -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/gapic_metadata.json b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/gapic_metadata.json deleted file mode 100644 index 23a2f8a3..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/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_v1p4beta1", - "protoPackage": "google.cloud.asset.v1p4beta1", - "schema": "1.0", - "services": { - "AssetService": { - "clients": { - "grpc": { - "libraryClient": "AssetServiceClient", - "rpcs": { - "AnalyzeIamPolicy": { - "methods": [ - "analyze_iam_policy" - ] - }, - "ExportIamPolicyAnalysis": { - "methods": [ - "export_iam_policy_analysis" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AssetServiceAsyncClient", - "rpcs": { - "AnalyzeIamPolicy": { - "methods": [ - "analyze_iam_policy" - ] - }, - "ExportIamPolicyAnalysis": { - "methods": [ - "export_iam_policy_analysis" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/py.typed b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/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/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py deleted file mode 100644 index 4de65971..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py deleted file mode 100644 index 357f9520..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py +++ /dev/null @@ -1,22 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py deleted file mode 100644 index ba071f94..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,298 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.asset_v1p4beta1.types import asset_service -from google.cloud.asset_v1p4beta1.types import assets -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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: 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 analyze_iam_policy(self, - request: asset_service.AnalyzeIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: - r"""Analyzes IAM policies based on the specified request. Returns a - list of - [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] - matching the request. - - Args: - request (:class:`google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest`): - The request object. A request message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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_v1p4beta1.types.AnalyzeIamPolicyResponse: - A response message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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.parent", request.analysis_query.parent), - )), - ) - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def export_iam_policy_analysis(self, - request: asset_service.ExportIamPolicyAnalysisRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports IAM policy analysis based on the specified request. This - API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. The metadata contains - the request to help callers to map responses to requests. - - Args: - request (:class:`google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest`): - The request object. A request message for - [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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_v1p4beta1.types.ExportIamPolicyAnalysisResponse` The export IAM policy analysis response. This message is returned by the - [google.longrunning.Operations.GetOperation][] method - in the returned - [google.longrunning.Operation.response][] field. - - """ - # Create or coerce a protobuf request object. - request = asset_service.ExportIamPolicyAnalysisRequest(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_iam_policy_analysis, - 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.parent", request.analysis_query.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.ExportIamPolicyAnalysisResponse, - metadata_type=asset_service.ExportIamPolicyAnalysisRequest, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AssetServiceAsyncClient", -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py deleted file mode 100644 index 3e2d7472..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/client.py +++ /dev/null @@ -1,472 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.asset_v1p4beta1.types import asset_service -from google.cloud.asset_v1p4beta1.types import assets -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport, None] = None, - client_options: Optional[client_options_lib.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 (google.api_core.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. - 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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: - 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: - 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, - ) - - def analyze_iam_policy(self, - request: asset_service.AnalyzeIamPolicyRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.AnalyzeIamPolicyResponse: - r"""Analyzes IAM policies based on the specified request. Returns a - list of - [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] - matching the request. - - Args: - request (google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest): - The request object. A request message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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_v1p4beta1.types.AnalyzeIamPolicyResponse: - A response message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.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.parent", request.analysis_query.parent), - )), - ) - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def export_iam_policy_analysis(self, - request: asset_service.ExportIamPolicyAnalysisRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports IAM policy analysis based on the specified request. This - API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. The metadata contains - the request to help callers to map responses to requests. - - Args: - request (google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest): - The request object. A request message for - [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (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_v1p4beta1.types.ExportIamPolicyAnalysisResponse` The export IAM policy analysis response. This message is returned by the - [google.longrunning.Operations.GetOperation][] method - in the returned - [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.ExportIamPolicyAnalysisRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ExportIamPolicyAnalysisRequest): - request = asset_service.ExportIamPolicyAnalysisRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_iam_policy_analysis] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("analysis_query.parent", request.analysis_query.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.ExportIamPolicyAnalysisResponse, - metadata_type=asset_service.ExportIamPolicyAnalysisRequest, - ) - - # Done; return the response. - return response - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ( - "AssetServiceClient", -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py deleted file mode 100644 index 2c12069f..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py deleted file mode 100644 index 2ed2d012..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,195 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.cloud.asset_v1p4beta1.types import asset_service -from google.longrunning import operations_pb2 # type: ignore - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-asset', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -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: 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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # If the credentials is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - 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.export_iam_policy_analysis: gapic_v1.method.wrap_method( - self.export_iam_policy_analysis, - default_timeout=60.0, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def analyze_iam_policy(self) -> Callable[ - [asset_service.AnalyzeIamPolicyRequest], - Union[ - asset_service.AnalyzeIamPolicyResponse, - Awaitable[asset_service.AnalyzeIamPolicyResponse] - ]]: - raise NotImplementedError() - - @property - def export_iam_policy_analysis(self) -> Callable[ - [asset_service.ExportIamPolicyAnalysisRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - -__all__ = ( - 'AssetServiceTransport', -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py deleted file mode 100644 index e76518e7..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,304 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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_v1p4beta1.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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> 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 applicatin 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 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 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 = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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: ga_credentials.Credentials = None, - credentials_file: 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. - """ - # Sanity 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 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 based on the specified request. Returns a - list of - [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] - matching the request. - - 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.v1p4beta1.AssetService/AnalyzeIamPolicy', - request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, - response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, - ) - return self._stubs['analyze_iam_policy'] - - @property - def export_iam_policy_analysis(self) -> Callable[ - [asset_service.ExportIamPolicyAnalysisRequest], - operations_pb2.Operation]: - r"""Return a callable for the export iam policy analysis method over gRPC. - - Exports IAM policy analysis based on the specified request. This - API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. The metadata contains - the request to help callers to map responses to requests. - - Returns: - Callable[[~.ExportIamPolicyAnalysisRequest], - ~.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_iam_policy_analysis' not in self._stubs: - self._stubs['export_iam_policy_analysis'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis', - request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_iam_policy_analysis'] - - -__all__ = ( - 'AssetServiceGrpcTransport', -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py deleted file mode 100644 index 375ee7b5..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,308 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.asset_v1p4beta1.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: 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> 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 applicatin 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 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 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 = 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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. - """ - # Sanity 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 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 based on the specified request. Returns a - list of - [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult] - matching the request. - - 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.v1p4beta1.AssetService/AnalyzeIamPolicy', - request_serializer=asset_service.AnalyzeIamPolicyRequest.serialize, - response_deserializer=asset_service.AnalyzeIamPolicyResponse.deserialize, - ) - return self._stubs['analyze_iam_policy'] - - @property - def export_iam_policy_analysis(self) -> Callable[ - [asset_service.ExportIamPolicyAnalysisRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the export iam policy analysis method over gRPC. - - Exports IAM policy analysis based on the specified request. This - API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. The metadata contains - the request to help callers to map responses to requests. - - Returns: - Callable[[~.ExportIamPolicyAnalysisRequest], - 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_iam_policy_analysis' not in self._stubs: - self._stubs['export_iam_policy_analysis'] = self.grpc_channel.unary_unary( - '/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis', - request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['export_iam_policy_analysis'] - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py deleted file mode 100644 index a2cfd26f..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/__init__.py +++ /dev/null @@ -1,36 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 ( - AnalyzeIamPolicyRequest, - AnalyzeIamPolicyResponse, - ExportIamPolicyAnalysisRequest, - ExportIamPolicyAnalysisResponse, - IamPolicyAnalysisOutputConfig, - IamPolicyAnalysisQuery, -) -from .assets import ( - IamPolicyAnalysisResult, -) - -__all__ = ( - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'ExportIamPolicyAnalysisRequest', - 'ExportIamPolicyAnalysisResponse', - 'IamPolicyAnalysisOutputConfig', - 'IamPolicyAnalysisQuery', - 'IamPolicyAnalysisResult', -) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py deleted file mode 100644 index a7661b30..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/asset_service.py +++ /dev/null @@ -1,534 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.cloud.asset_v1p4beta1.types import assets -from google.protobuf import duration_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p4beta1', - manifest={ - 'IamPolicyAnalysisQuery', - 'AnalyzeIamPolicyRequest', - 'AnalyzeIamPolicyResponse', - 'IamPolicyAnalysisOutputConfig', - 'ExportIamPolicyAnalysisRequest', - 'ExportIamPolicyAnalysisResponse', - }, -) - - -class IamPolicyAnalysisQuery(proto.Message): - r"""IAM policy analysis query message. - Attributes: - parent (str): - Required. The relative name of the root - asset. Only resources and IAM policies within - the parent will be analyzed. This can only be an - organization number (such as - "organizations/123") or a folder number (such as - "folders/123"). - resource_selector (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery.ResourceSelector): - Optional. Specifies a resource for analysis. - Leaving it empty means ANY. - identity_selector (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery.IdentitySelector): - Optional. Specifies an identity for analysis. - Leaving it empty means ANY. - access_selector (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery.AccessSelector): - Optional. Specifies roles or permissions for - analysis. Leaving it empty means ANY. - """ - - 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. At least one of - [ResourceSelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.ResourceSelector], - [IdentitySelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.IdentitySelector] - or - [AccessSelector][google.cloud.asset.v1p4beta1.IamPolicyAnalysisQuery.AccessSelector] - must be specified in a request. - - Attributes: - full_resource_name (str): - Required. The `full resource - name `__ - . - """ - - full_resource_name = 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 members in `IAM - policy - binding `__. - """ - - identity = 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 - identities and resources matching any of them. - - Attributes: - roles (Sequence[str]): - Optional. The roles to appear in result. - permissions (Sequence[str]): - Optional. The permissions to appear in - result. - """ - - roles = proto.RepeatedField( - proto.STRING, - number=1, - ) - permissions = proto.RepeatedField( - proto.STRING, - number=2, - ) - - parent = proto.Field( - proto.STRING, - number=1, - ) - resource_selector = proto.Field( - proto.MESSAGE, - number=2, - message=ResourceSelector, - ) - identity_selector = proto.Field( - proto.MESSAGE, - number=3, - message=IdentitySelector, - ) - access_selector = proto.Field( - proto.MESSAGE, - number=4, - message=AccessSelector, - ) - - -class AnalyzeIamPolicyRequest(proto.Message): - r"""A request message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. - - Attributes: - analysis_query (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery): - Required. The request query. - options (google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest.Options): - Optional. The request options. - """ - - class Options(proto.Message): - r"""Contains request 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 [identity_selector][] is specified, the identity in the - result will be determined by the selector, and this flag - will have no effect. - - 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 [access_selector][] is specified, the access section of - the result will be determined by the selector, and this flag - will have no effect. - - Default is false. - expand_resources (bool): - Optional. If true, 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 GCP folder, the results will also include - resources in that folder with permission P. - - If [resource_selector][] is specified, the resource section - of the result will be determined by the selector, and this - flag will have no effect. Default is false. - output_resource_edges (bool): - Optional. If true, the result will output - resource edges, starting from the policy - attached resource, to any expanded resources. - Default is false. - output_group_edges (bool): - Optional. If true, the result will output - group identity edges, starting from the - binding's group members, to any expanded - identities. 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 ExportIamPolicyAnalysis 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 GCP folder F, then - user A potentially has access to the GCP folder F. And those - advanced analysis results will be included in - [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. - - Another example, if the request analyzes for who has - permission P to a GCP 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 GCP folder F, - then user A potentially has access to the GCP folder F. And - those advanced analysis results will be included in - [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. - - Default is false. - 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. - """ - - expand_groups = proto.Field( - proto.BOOL, - number=1, - ) - expand_roles = proto.Field( - proto.BOOL, - number=2, - ) - expand_resources = proto.Field( - proto.BOOL, - number=3, - ) - output_resource_edges = proto.Field( - proto.BOOL, - number=4, - ) - output_group_edges = proto.Field( - proto.BOOL, - number=5, - ) - analyze_service_account_impersonation = proto.Field( - proto.BOOL, - number=6, - ) - execution_timeout = proto.Field( - proto.MESSAGE, - number=7, - message=duration_pb2.Duration, - ) - - analysis_query = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - options = proto.Field( - proto.MESSAGE, - number=2, - message=Options, - ) - - -class AnalyzeIamPolicyResponse(proto.Message): - r"""A response message for - [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. - - Attributes: - main_analysis (google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyResponse.IamPolicyAnalysis): - The main analysis that matches the original - request. - service_account_impersonation_analysis (Sequence[google.cloud.asset_v1p4beta1.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.v1p4beta1.AnalyzeIamPolicyResponse.main_analysis] - and - [service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis] - have been fully explored to answer the query in the request. - non_critical_errors (Sequence[google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState]): - A list of non-critical errors happened during the request - handling to explain why ``fully_explored`` is false, or - empty if no error happened. - """ - - class IamPolicyAnalysis(proto.Message): - r"""An analysis message to group the query and results. - Attributes: - analysis_query (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery): - The analysis query. - analysis_results (Sequence[google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult]): - A list of - [IamPolicyAnalysisResult][google.cloud.asset.v1p4beta1.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.v1p4beta1.AnalyzeIamPolicyResponse.IamPolicyAnalysis.analysis_results] - have been fully explored to answer the query. - """ - - analysis_query = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - analysis_results = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=assets.IamPolicyAnalysisResult, - ) - fully_explored = proto.Field( - proto.BOOL, - number=3, - ) - - main_analysis = proto.Field( - proto.MESSAGE, - number=1, - message=IamPolicyAnalysis, - ) - service_account_impersonation_analysis = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=IamPolicyAnalysis, - ) - fully_explored = proto.Field( - proto.BOOL, - number=3, - ) - non_critical_errors = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=assets.IamPolicyAnalysisResult.AnalysisState, - ) - - -class IamPolicyAnalysisOutputConfig(proto.Message): - r"""Output configuration for export IAM policy analysis - destination. - - Attributes: - gcs_destination (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig.GcsDestination): - Destination on Cloud Storage. - """ - - 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. For example: - "gs://bucket_name/object_name". See `Viewing and Editing - Object - Metadata `__ - for more information. - """ - - uri = proto.Field( - proto.STRING, - number=1, - ) - - gcs_destination = proto.Field( - proto.MESSAGE, - number=1, - oneof='destination', - message=GcsDestination, - ) - - -class ExportIamPolicyAnalysisRequest(proto.Message): - r"""A request message for - [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. - - Attributes: - analysis_query (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery): - Required. The request query. - options (google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest.Options): - Optional. The request options. - output_config (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig): - Required. Output configuration indicating - where the results will be output to. - """ - - class Options(proto.Message): - r"""Contains request 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 [identity_selector][] is specified, the identity in the - result will be determined by the selector, and this flag - will have no effect. - - 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 [access_selector][] is specified, the access section of - the result will be determined by the selector, and this flag - will have no effect. - - Default is false. - expand_resources (bool): - Optional. If true, 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 GCP folder, the results will also include - resources in that folder with permission P. - - If [resource_selector][] is specified, the resource section - of the result will be determined by the selector, and this - flag will have no effect. Default is false. - output_resource_edges (bool): - Optional. If true, the result will output - resource edges, starting from the policy - attached resource, to any expanded resources. - Default is false. - output_group_edges (bool): - Optional. If true, the result will output - group identity edges, starting from the - binding's group members, to any expanded - identities. 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. - - 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 GCP folder F, then - user A potentially has access to the GCP folder F. And those - advanced analysis results will be included in - [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. - - Another example, if the request analyzes for who has - permission P to a GCP 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 GCP folder F, - then user A potentially has access to the GCP folder F. And - those advanced analysis results will be included in - [AnalyzeIamPolicyResponse.service_account_impersonation_analysis][google.cloud.asset.v1p4beta1.AnalyzeIamPolicyResponse.service_account_impersonation_analysis]. - - Default is false. - """ - - expand_groups = proto.Field( - proto.BOOL, - number=1, - ) - expand_roles = proto.Field( - proto.BOOL, - number=2, - ) - expand_resources = proto.Field( - proto.BOOL, - number=3, - ) - output_resource_edges = proto.Field( - proto.BOOL, - number=4, - ) - output_group_edges = proto.Field( - proto.BOOL, - number=5, - ) - analyze_service_account_impersonation = proto.Field( - proto.BOOL, - number=6, - ) - - analysis_query = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisQuery', - ) - options = proto.Field( - proto.MESSAGE, - number=2, - message=Options, - ) - output_config = proto.Field( - proto.MESSAGE, - number=3, - message='IamPolicyAnalysisOutputConfig', - ) - - -class ExportIamPolicyAnalysisResponse(proto.Message): - r"""The export IAM policy analysis response. This message is returned by - the [google.longrunning.Operations.GetOperation][] method in the - returned [google.longrunning.Operation.response][] field. - - Attributes: - output_config (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisOutputConfig): - Output configuration indicating where the - results were output to. - """ - - output_config = proto.Field( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisOutputConfig', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py b/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py deleted file mode 100644 index e3f1607d..00000000 --- a/owl-bot-staging/v1p4beta1/google/cloud/asset_v1p4beta1/types/assets.py +++ /dev/null @@ -1,302 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 proto # type: ignore - -from google.iam.v1 import policy_pb2 # type: ignore -from google.rpc import code_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.asset.v1p4beta1', - manifest={ - 'IamPolicyAnalysisResult', - }, -) - - -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 name of the resource to which the - [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] - policy attaches. - iam_binding (google.iam.v1.policy_pb2.Binding): - The Cloud IAM policy binding under analysis. - access_control_lists (Sequence[google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AccessControlList]): - The access control lists derived from the - [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] - that match or potentially match resource and access - selectors specified in the request. - identity_list (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.IdentityList): - The identity list derived from members of the - [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] - that match or potentially match identity selector specified - in the request. - fully_explored (bool): - Represents whether all nodes in the transitive closure of - the - [iam_binding][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.iam_binding] - node have been explored. - """ - - class AnalysisState(proto.Message): - r"""Represents analysis state of each node in the result graph or - non-critical errors in the response. - - Attributes: - code (google.rpc.code_pb2.Code): - The Google standard error code that best describes the - state. For example: - - - OK means the node has been successfully explored; - - PERMISSION_DENIED means an access denied error is - encountered; - - DEADLINE_EXCEEDED means the node hasn't been explored in - time; - cause (str): - The human-readable description of the cause - of failure. - """ - - code = proto.Field( - proto.ENUM, - number=1, - enum=code_pb2.Code, - ) - cause = proto.Field( - proto.STRING, - number=2, - ) - - class Resource(proto.Message): - r"""A GCP resource that appears in an access control list. - Attributes: - full_resource_name (str): - The `full resource - name `__. - analysis_state (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState): - The analysis state of this resource node. - """ - - full_resource_name = proto.Field( - proto.STRING, - number=1, - ) - analysis_state = proto.Field( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.AnalysisState', - ) - - class Access(proto.Message): - r"""A role or permission that appears in an access control list. - Attributes: - role (str): - The role. - permission (str): - The permission. - analysis_state (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState): - The analysis state of this access node. - """ - - role = proto.Field( - proto.STRING, - number=1, - oneof='oneof_access', - ) - permission = proto.Field( - proto.STRING, - number=2, - oneof='oneof_access', - ) - analysis_state = proto.Field( - proto.MESSAGE, - number=3, - message='IamPolicyAnalysisResult.AnalysisState', - ) - - class Edge(proto.Message): - r"""A directional edge. - Attributes: - source_node (str): - The source node of the edge. - target_node (str): - The target node of the edge. - """ - - source_node = proto.Field( - proto.STRING, - number=1, - ) - target_node = proto.Field( - proto.STRING, - number=2, - ) - - class Identity(proto.Message): - r"""An identity that appears in an access control list. - Attributes: - name (str): - The identity name in any form of members appear in `IAM - policy - binding `__, - such as: - - - user:foo@google.com - - group:group1@google.com - - serviceAccount:s1@prj1.iam.gserviceaccount.com - - projectOwner:some_project_id - - domain:google.com - - allUsers - - etc. - analysis_state (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.AnalysisState): - The analysis state of this identity node. - """ - - name = proto.Field( - proto.STRING, - number=1, - ) - analysis_state = proto.Field( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.AnalysisState', - ) - - 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 (Sequence[google.cloud.asset_v1p4beta1.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 (Sequence[google.cloud.asset_v1p4beta1.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 (Sequence[google.cloud.asset_v1p4beta1.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.v1p4beta1.IamPolicyAnalysisResult.Edge.source_node] - contains the full resource name of a parent resource and - [Edge.target_node][google.cloud.asset.v1p4beta1.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. - """ - - resources = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisResult.Resource', - ) - accesses = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.Access', - ) - resource_edges = proto.RepeatedField( - proto.MESSAGE, - number=3, - message='IamPolicyAnalysisResult.Edge', - ) - - class IdentityList(proto.Message): - r""" - Attributes: - identities (Sequence[google.cloud.asset_v1p4beta1.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 (Sequence[google.cloud.asset_v1p4beta1.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.v1p4beta1.IamPolicyAnalysisResult.IdentityList.identities]. - The - [Edge.source_node][google.cloud.asset.v1p4beta1.IamPolicyAnalysisResult.Edge.source_node] - contains a group, such as "group:parent@google.com". The - [Edge.target_node][google.cloud.asset.v1p4beta1.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 = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='IamPolicyAnalysisResult.Identity', - ) - group_edges = proto.RepeatedField( - proto.MESSAGE, - number=2, - message='IamPolicyAnalysisResult.Edge', - ) - - attached_resource_full_name = proto.Field( - proto.STRING, - number=1, - ) - iam_binding = proto.Field( - proto.MESSAGE, - number=2, - message=policy_pb2.Binding, - ) - access_control_lists = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=AccessControlList, - ) - identity_list = proto.Field( - proto.MESSAGE, - number=4, - message=IdentityList, - ) - fully_explored = proto.Field( - proto.BOOL, - number=5, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/v1p4beta1/mypy.ini b/owl-bot-staging/v1p4beta1/mypy.ini deleted file mode 100644 index 4505b485..00000000 --- a/owl-bot-staging/v1p4beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p4beta1/noxfile.py b/owl-bot-staging/v1p4beta1/noxfile.py deleted file mode 100644 index f7008fb0..00000000 --- a/owl-bot-staging/v1p4beta1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/asset_v1p4beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - 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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) diff --git a/owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py b/owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py deleted file mode 100644 index b3ee3fcb..00000000 --- a/owl-bot-staging/v1p4beta1/scripts/fixup_asset_v1p4beta1_keywords.py +++ /dev/null @@ -1,177 +0,0 @@ -#! /usr/bin/env python3 -# -*- 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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', 'options', ), - 'export_iam_policy_analysis': ('analysis_query', 'output_config', 'options', ), - } - - 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: not a.keyword.value 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/v1p4beta1/setup.py b/owl-bot-staging/v1p4beta1/setup.py deleted file mode 100644 index 1aece31b..00000000 --- a/owl-bot-staging/v1p4beta1/setup.py +++ /dev/null @@ -1,53 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-asset', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1p4beta1/tests/__init__.py b/owl-bot-staging/v1p4beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p4beta1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1p4beta1/tests/unit/__init__.py b/owl-bot-staging/v1p4beta1/tests/unit/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p4beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1p4beta1/tests/unit/gapic/__init__.py b/owl-bot-staging/v1p4beta1/tests/unit/gapic/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p4beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py b/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py b/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py deleted file mode 100644 index dcc13156..00000000 --- a/owl-bot-staging/v1p4beta1/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py +++ /dev/null @@ -1,1254 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -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_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceAsyncClient -from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceClient -from google.cloud.asset_v1p4beta1.services.asset_service import transports -from google.cloud.asset_v1p4beta1.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.asset_v1p4beta1.types import asset_service -from google.cloud.asset_v1p4beta1.types import assets -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - ] - 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"), -]) -@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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@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"), -]) -@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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -def test_asset_service_client_client_options_from_dict(): - with mock.patch('google.cloud.asset_v1p4beta1.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, - ) - - -def test_analyze_iam_policy(transport: str = 'grpc', request_type=asset_service.AnalyzeIamPolicyRequest): - 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_from_dict(): - test_analyze_iam_policy(request_type=dict) - - -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.parent = 'analysis_query.parent/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.parent=analysis_query.parent/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.parent = 'analysis_query.parent/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.parent=analysis_query.parent/value', - ) in kw['metadata'] - - -def test_export_iam_policy_analysis(transport: str = 'grpc', request_type=asset_service.ExportIamPolicyAnalysisRequest): - 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_iam_policy_analysis), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.export_iam_policy_analysis(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.ExportIamPolicyAnalysisRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_iam_policy_analysis_from_dict(): - test_export_iam_policy_analysis(request_type=dict) - - -def test_export_iam_policy_analysis_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_iam_policy_analysis), - '__call__') as call: - client.export_iam_policy_analysis() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ExportIamPolicyAnalysisRequest() - - -@pytest.mark.asyncio -async def test_export_iam_policy_analysis_async(transport: str = 'grpc_asyncio', request_type=asset_service.ExportIamPolicyAnalysisRequest): - 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_iam_policy_analysis), - '__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_iam_policy_analysis(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.ExportIamPolicyAnalysisRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_iam_policy_analysis_async_from_dict(): - await test_export_iam_policy_analysis_async(request_type=dict) - - -def test_export_iam_policy_analysis_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.ExportIamPolicyAnalysisRequest() - - request.analysis_query.parent = 'analysis_query.parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_iam_policy_analysis), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.export_iam_policy_analysis(request) - - # Establish that the 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.parent=analysis_query.parent/value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_export_iam_policy_analysis_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.ExportIamPolicyAnalysisRequest() - - request.analysis_query.parent = 'analysis_query.parent/value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.export_iam_policy_analysis), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.export_iam_policy_analysis(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.parent=analysis_query.parent/value', - ) in kw['metadata'] - - -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 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, -]) -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() - -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_v1p4beta1.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 = ( - 'analyze_iam_policy', - 'export_iam_policy_analysis', - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -@requires_google_auth_gte_1_25_0 -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_v1p4beta1.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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_base_transport_with_credentials_file_old_google_auth(): - # 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_v1p4beta1.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=( - '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_v1p4beta1.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() - - -@requires_google_auth_gte_1_25_0 -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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_auth_adc_old_google_auth(): - # 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=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -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, - ], -) -@requires_google_auth_lt_1_25_0 -def test_asset_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@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_host_no_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_host_with_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:8000' - -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_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_withDEFAULT_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) diff --git a/owl-bot-staging/v1p5beta1/.coveragerc b/owl-bot-staging/v1p5beta1/.coveragerc deleted file mode 100644 index 3425850c..00000000 --- a/owl-bot-staging/v1p5beta1/.coveragerc +++ /dev/null @@ -1,17 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/asset/__init__.py -exclude_lines = - # Re-enable the standard pragma - pragma: NO COVER - # Ignore debug-only repr - def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound 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/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 31650c9a..00000000 --- a/owl-bot-staging/v1p5beta1/docs/asset_v1p5beta1/types.rst +++ /dev/null @@ -1,7 +0,0 @@ -Types for Google Cloud Asset v1p5beta1 API -========================================== - -.. automodule:: google.cloud.asset_v1p5beta1.types - :members: - :undoc-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 3aa26721..00000000 --- a/owl-bot-staging/v1p5beta1/docs/conf.py +++ /dev/null @@ -1,376 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 = "1.6.3" - -# 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 master toctree document. -master_doc = "index" - -# General information about the project. -project = u"google-cloud-asset" -copyright = u"2020, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-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 = [ - ( - master_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 = [ - ( - master_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 = [ - ( - master_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 a84dfdea..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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.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/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 b6d6b65b..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/__init__.py +++ /dev/null @@ -1,34 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 .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 3d280aa7..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/gapic_metadata.json +++ /dev/null @@ -1,33 +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" - ] - } - } - } - } - } - } -} 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 4de65971..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/__init__.py +++ /dev/null @@ -1,15 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 357f9520..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 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 05e2db9c..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,237 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # 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 .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 - - asset_path = staticmethod(AssetServiceClient.asset_path) - parse_asset_path = staticmethod(AssetServiceClient.parse_asset_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 - - @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: ga_credentials.Credentials = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: 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: asset_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - Args: - request (:class:`google.cloud.asset_v1p5beta1.types.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: - 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. - request = asset_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 1ebfd59d..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/client.py +++ /dev/null @@ -1,418 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 distutils import util -import os -import re -from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union -import pkg_resources - -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -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 .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport - - -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 - - def get_transport_class(cls, - label: 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 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 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 {} - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport, None] = None, - client_options: Optional[client_options_lib.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 (google.api_core.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. - 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() - - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) - - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) - - # 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: - 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: - 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, - ) - - def list_assets(self, - request: asset_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists assets with time and resource types and returns - paged results in response. - - Args: - request (google.cloud.asset_v1p5beta1.types.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: - 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. - # 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) - - # 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 - - - - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-asset", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__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 13ea4412..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py +++ /dev/null @@ -1,141 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional - -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) -> Iterable[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) -> Iterable[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) -> AsyncIterable[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) -> AsyncIterable[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 2c12069f..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py +++ /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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry['grpc'] = AssetServiceGrpcTransport -_transport_registry['grpc_asyncio'] = AssetServiceGrpcAsyncIOTransport - -__all__ = ( - 'AssetServiceTransport', - 'AssetServiceGrpcTransport', - 'AssetServiceGrpcAsyncIOTransport', -) 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 757cf600..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,175 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 -import packaging.version -import pkg_resources - -import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -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 - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - 'google-cloud-asset', - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - -try: - # google.auth.__version__ was added in 1.26.0 - _GOOGLE_AUTH_VERSION = google.auth.__version__ -except AttributeError: - try: # try pkg_resources if it is available - _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version - except pkg_resources.DistributionNotFound: # pragma: NO COVER - _GOOGLE_AUTH_VERSION = None - - -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: 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, - **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. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - scopes_kwargs = self._get_scopes_kwargs(self._host, 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) - - # If the credentials is 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 - - # TODO(busunkim): This method is in the base transport - # to avoid duplicating code across the transport classes. These functions - # should be deleted once the minimum required versions of google-auth is increased. - - # TODO: Remove this function once google-auth >= 1.25.0 is required - @classmethod - def _get_scopes_kwargs(cls, host: str, scopes: Optional[Sequence[str]]) -> Dict[str, Optional[Sequence[str]]]: - """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" - - scopes_kwargs = {} - - if _GOOGLE_AUTH_VERSION and ( - packaging.version.parse(_GOOGLE_AUTH_VERSION) - >= packaging.version.parse("1.25.0") - ): - scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} - else: - scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} - - return scopes_kwargs - - 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, - ), - } - - @property - def list_assets(self) -> Callable[ - [asset_service.ListAssetsRequest], - Union[ - asset_service.ListAssetsResponse, - Awaitable[asset_service.ListAssetsResponse] - ]]: - 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 40fdf10e..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,253 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -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 .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: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: 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, - ) -> 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 applicatin 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 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 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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: ga_credentials.Credentials = None, - credentials_file: 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'] - - -__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 49dc7185..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,257 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -import packaging.version - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.asset_v1p5beta1.types import asset_service -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: 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: ga_credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - ) -> 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 applicatin 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 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 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, - ) - - if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( - self._host, - credentials=self._credentials, - credentials_file=credentials_file, - 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'] - - -__all__ = ( - 'AssetServiceGrpcAsyncIOTransport', -) 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 5f29a3d9..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/__init__.py +++ /dev/null @@ -1,32 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 301f423f..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/asset_service.py +++ /dev/null @@ -1,140 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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.""" - 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-number]" - (such as "projects/my-project-id"), or - "projects/[project-id]" (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 2018-10-02 - UTC (inclusive) and the current time. 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 (Sequence[str]): - A list of asset types of which to take a snapshot for. For - example: "compute.googleapis.com/Disk". If specified, only - matching assets will be returned. 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 = proto.Field( - proto.STRING, - number=1, - ) - read_time = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - asset_types = proto.RepeatedField( - proto.STRING, - number=3, - ) - content_type = proto.Field( - proto.ENUM, - number=4, - enum='ContentType', - ) - page_size = proto.Field( - proto.INT32, - number=5, - ) - page_token = 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 (Sequence[google.cloud.asset_v1p5beta1.types.Asset]): - Assets. - next_page_token (str): - Token to retrieve the next page of results. - Set to empty if there are no remaining results. - """ - - @property - def raw_page(self): - return self - - read_time = proto.Field( - proto.MESSAGE, - number=1, - message=timestamp_pb2.Timestamp, - ) - assets = proto.RepeatedField( - proto.MESSAGE, - number=2, - message=gca_assets.Asset, - ) - next_page_token = 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 79781961..00000000 --- a/owl-bot-staging/v1p5beta1/google/cloud/asset_v1p5beta1/types/assets.py +++ /dev/null @@ -1,194 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 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"""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_v1p5beta1.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. - org_policy (Sequence[google.cloud.orgpolicy.v1.orgpolicy_pb2.Policy]): - Representation of the Cloud Organization - Policy set on an asset. For each asset, there - could be multiple Organization policies with - different constraints. - access_policy (google.identity.accesscontextmanager.v1.access_policy_pb2.AccessPolicy): - - access_level (google.identity.accesscontextmanager.v1.access_level_pb2.AccessLevel): - - service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): - - ancestors (Sequence[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 = proto.Field( - proto.STRING, - number=1, - ) - asset_type = proto.Field( - proto.STRING, - number=2, - ) - resource = proto.Field( - proto.MESSAGE, - number=3, - message='Resource', - ) - iam_policy = proto.Field( - proto.MESSAGE, - number=4, - message=policy_pb2.Policy, - ) - org_policy = proto.RepeatedField( - proto.MESSAGE, - number=6, - message=orgpolicy_pb2.Policy, - ) - access_policy = proto.Field( - proto.MESSAGE, - number=7, - oneof='access_context_policy', - message=access_policy_pb2.AccessPolicy, - ) - access_level = proto.Field( - proto.MESSAGE, - number=8, - oneof='access_context_policy', - message=access_level_pb2.AccessLevel, - ) - service_perimeter = proto.Field( - proto.MESSAGE, - number=9, - oneof='access_context_policy', - message=service_perimeter_pb2.ServicePerimeter, - ) - ancestors = proto.RepeatedField( - proto.STRING, - number=10, - ) - - -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 = proto.Field( - proto.STRING, - number=1, - ) - discovery_document_uri = proto.Field( - proto.STRING, - number=2, - ) - discovery_name = proto.Field( - proto.STRING, - number=3, - ) - resource_url = proto.Field( - proto.STRING, - number=4, - ) - parent = proto.Field( - proto.STRING, - number=5, - ) - data = 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 4505b485..00000000 --- a/owl-bot-staging/v1p5beta1/mypy.ini +++ /dev/null @@ -1,3 +0,0 @@ -[mypy] -python_version = 3.6 -namespace_packages = True diff --git a/owl-bot-staging/v1p5beta1/noxfile.py b/owl-bot-staging/v1p5beta1/noxfile.py deleted file mode 100644 index e1a406a9..00000000 --- a/owl-bot-staging/v1p5beta1/noxfile.py +++ /dev/null @@ -1,132 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -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") - - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", -] - -@nox.session(python=['3.6', '3.7', '3.8', '3.9']) -def unit(session): - """Run the unit test suite.""" - - session.install('coverage', 'pytest', 'pytest-cov', 'asyncmock', 'pytest-asyncio') - session.install('-e', '.') - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/asset_v1p5beta1/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)) - ) - - -@nox.session(python='3.7') -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=['3.6', '3.7']) -def mypy(session): - """Run the type checker.""" - session.install('mypy', 'types-pkg_resources') - 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='3.6') -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx<3.0.0", "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", ""), - ) 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 9eb4f0f8..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 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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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: not a.keyword.value 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 1aece31b..00000000 --- a/owl-bot-staging/v1p5beta1/setup.py +++ /dev/null @@ -1,53 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 - -version = '0.1.0' - -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() - -setuptools.setup( - name='google-cloud-asset', - version=version, - long_description=readme, - packages=setuptools.PEP420PackageFinder.find(), - namespace_packages=('google', 'google.cloud'), - platforms='Posix; MacOS X; Windows', - include_package_data=True, - install_requires=( - 'google-api-core[grpc] >= 1.27.0, < 2.0.0dev', - 'libcst >= 0.2.5', - 'proto-plus >= 1.15.0', - 'packaging >= 14.3', 'grpc-google-iam-v1 >= 0.12.3, < 0.13dev', ), - python_requires='>=3.6', - classifiers=[ - 'Development Status :: 3 - Alpha', - 'Intended Audience :: Developers', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Topic :: Internet', - 'Topic :: Software Development :: Libraries :: Python Modules', - ], - zip_safe=False, -) diff --git a/owl-bot-staging/v1p5beta1/tests/__init__.py b/owl-bot-staging/v1p5beta1/tests/__init__.py deleted file mode 100644 index b54a5fcc..00000000 --- a/owl-bot-staging/v1p5beta1/tests/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 b54a5fcc..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/__init__.py +++ /dev/null @@ -1,16 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 6e4c0b98..00000000 --- a/owl-bot-staging/v1p5beta1/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py +++ /dev/null @@ -1,1266 +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 -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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 mock -import packaging.version - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - - -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.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.services.asset_service.transports.base import _GOOGLE_AUTH_VERSION -from google.cloud.asset_v1p5beta1.types import asset_service -from google.cloud.asset_v1p5beta1.types import assets -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively -# through google-api-core: -# - Delete the auth "less than" test cases -# - Delete these pytest markers (Make the "greater than or equal to" tests the default). -requires_google_auth_lt_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), - reason="This test requires google-auth < 1.25.0", -) -requires_google_auth_gte_1_25_0 = pytest.mark.skipif( - packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), - reason="This test requires google-auth >= 1.25.0", -) - -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", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_info(client_class): - 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) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_service_account_always_use_jwt(client_class): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - client = client_class(credentials=creds) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AssetServiceGrpcTransport, "grpc"), - (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_service_account_always_use_jwt_true(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) - - -@pytest.mark.parametrize("client_class", [ - AssetServiceClient, - AssetServiceAsyncClient, -]) -def test_asset_service_client_from_service_account_file(client_class): - 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") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - available_transports = [ - transports.AssetServiceGrpcTransport, - ] - 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"), -]) -@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(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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - # 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() - - # 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() - - # 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) - 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, - ) - -@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"), -]) -@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) - - 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, - ) - - # 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() - 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, - ) - - # 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() - 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, - ) - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -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) - 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, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - (AssetServiceAsyncClient, transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), -]) -def test_asset_service_client_client_options_credentials_file(client_class, transport_class, transport_name): - # 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) - 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, - ) - - -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, - ) - - -def test_list_assets(transport: str = 'grpc', request_type=asset_service.ListAssetsRequest): - 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_from_dict(): - test_list_assets(request_type=dict) - - -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_pager(): - 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: - # 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 = [i for i in pager] - assert len(results) == 6 - assert all(isinstance(i, assets.Asset) - for i in results) - -def test_list_assets_pages(): - 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: - # 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: - 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 = [] - async for page_ in (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 - - -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 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, -]) -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() - -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()) - - -@requires_google_auth_gte_1_25_0 -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", - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_base_transport_with_credentials_file_old_google_auth(): - # 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=( - '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() - - -@requires_google_auth_gte_1_25_0 -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, - ) - - -@requires_google_auth_lt_1_25_0 -def test_asset_service_auth_adc_old_google_auth(): - # 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=( 'https://www.googleapis.com/auth/cloud-platform',), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AssetServiceGrpcTransport, - transports.AssetServiceGrpcAsyncIOTransport, - ], -) -@requires_google_auth_gte_1_25_0 -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, - ], -) -@requires_google_auth_lt_1_25_0 -def test_asset_service_transport_auth_adc_old_google_auth(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") - adc.assert_called_once_with(scopes=( - 'https://www.googleapis.com/auth/cloud-platform', -), - quota_project_id="octopus", - ) - - -@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_host_no_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:443' - - -def test_asset_service_host_with_port(): - client = AssetServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudasset.googleapis.com:8000'), - ) - assert client.transport._host == 'cloudasset.googleapis.com:8000' - -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_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_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_withDEFAULT_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) diff --git a/scripts/fixup_asset_v1_keywords.py b/scripts/fixup_asset_v1_keywords.py index cfef8db5..4a9e79e9 100644 --- a/scripts/fixup_asset_v1_keywords.py +++ b/scripts/fixup_asset_v1_keywords.py @@ -48,7 +48,7 @@ class assetCallTransformer(cst.CSTTransformer): 'get_feed': ('name', ), 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), 'list_feeds': ('parent', ), - 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), + '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', ), 'update_feed': ('feed', 'update_mask', ), } diff --git a/tests/unit/gapic/asset_v1/test_asset_service.py b/tests/unit/gapic/asset_v1/test_asset_service.py index d6140d64..25543608 100644 --- a/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1/test_asset_service.py @@ -38,9 +38,6 @@ 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.services.asset_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.asset_v1.services.asset_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -55,8 +52,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -67,16 +65,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -134,6 +122,34 @@ def test_asset_service_client_from_service_account_info(client_class): assert client.transport._host == "cloudasset.googleapis.com:443" +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_asset_service_client_service_account_always_use_jwt_true( + 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) + + @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -3371,7 +3387,6 @@ def test_asset_service_transport_auth_adc_old_google_auth(transport_class): (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -3400,79 +3415,6 @@ def test_asset_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "cloudasset.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], @@ -3492,7 +3434,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -3596,7 +3538,7 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -3640,7 +3582,7 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py index 86324791..b77607ea 100644 --- a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -35,9 +35,6 @@ 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.services.asset_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.asset_v1p1beta1.services.asset_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -47,8 +44,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -59,16 +57,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -126,6 +114,34 @@ def test_asset_service_client_from_service_account_info(client_class): assert client.transport._host == "cloudasset.googleapis.com:443" +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_asset_service_client_service_account_always_use_jwt_true( + 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) + + @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -1475,7 +1491,6 @@ def test_asset_service_transport_auth_adc_old_google_auth(transport_class): (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -1504,79 +1519,6 @@ def test_asset_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "cloudasset.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], @@ -1596,7 +1538,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1700,7 +1642,7 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -1744,7 +1686,7 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py index 8369ff2f..5cac32a1 100644 --- a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -34,9 +34,6 @@ 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.services.asset_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.asset_v1p2beta1.services.asset_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -46,8 +43,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -58,16 +56,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -125,6 +113,34 @@ def test_asset_service_client_from_service_account_info(client_class): assert client.transport._host == "cloudasset.googleapis.com:443" +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_asset_service_client_service_account_always_use_jwt_true( + 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) + + @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -1697,7 +1713,6 @@ def test_asset_service_transport_auth_adc_old_google_auth(transport_class): (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -1726,79 +1741,6 @@ def test_asset_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "cloudasset.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], @@ -1818,7 +1760,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1922,7 +1864,7 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -1966,7 +1908,7 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py index 6d21bcbc..2da5260c 100644 --- a/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py @@ -37,9 +37,6 @@ from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceAsyncClient from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceClient from google.cloud.asset_v1p4beta1.services.asset_service import transports -from google.cloud.asset_v1p4beta1.services.asset_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.asset_v1p4beta1.services.asset_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -51,8 +48,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -63,16 +61,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -130,6 +118,34 @@ def test_asset_service_client_from_service_account_info(client_class): assert client.transport._host == "cloudasset.googleapis.com:443" +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_asset_service_client_service_account_always_use_jwt_true( + 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) + + @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -993,7 +1009,6 @@ def test_asset_service_transport_auth_adc_old_google_auth(transport_class): (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -1022,79 +1037,6 @@ def test_asset_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "cloudasset.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], @@ -1114,7 +1056,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1218,7 +1160,7 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -1262,7 +1204,7 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ diff --git a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py index 55f017d4..5d9c1140 100644 --- a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -35,9 +35,6 @@ 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.services.asset_service.transports.base import ( - _API_CORE_VERSION, -) from google.cloud.asset_v1p5beta1.services.asset_service.transports.base import ( _GOOGLE_AUTH_VERSION, ) @@ -48,8 +45,9 @@ import google.auth -# TODO(busunkim): Once google-api-core >= 1.26.0 is required: -# - Delete all the api-core and auth "less than" test cases +# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively +# through google-api-core: +# - Delete the auth "less than" test cases # - Delete these pytest markers (Make the "greater than or equal to" tests the default). requires_google_auth_lt_1_25_0 = pytest.mark.skipif( packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), @@ -60,16 +58,6 @@ reason="This test requires google-auth >= 1.25.0", ) -requires_api_core_lt_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), - reason="This test requires google-api-core < 1.26.0", -) - -requires_api_core_gte_1_26_0 = pytest.mark.skipif( - packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), - reason="This test requires google-api-core >= 1.26.0", -) - def client_cert_source_callback(): return b"cert bytes", b"key bytes" @@ -127,6 +115,34 @@ def test_asset_service_client_from_service_account_info(client_class): assert client.transport._host == "cloudasset.googleapis.com:443" +@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) +def test_asset_service_client_service_account_always_use_jwt(client_class): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + client = client_class(credentials=creds) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AssetServiceGrpcTransport, "grpc"), + (transports.AssetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_asset_service_client_service_account_always_use_jwt_true( + 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) + + @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() @@ -935,7 +951,6 @@ def test_asset_service_transport_auth_adc_old_google_auth(transport_class): (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), ], ) -@requires_api_core_gte_1_26_0 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. @@ -964,79 +979,6 @@ def test_asset_service_transport_create_channel(transport_class, grpc_helpers): ) -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_old_api_core( - 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") - - create_channel.assert_called_with( - "cloudasset.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.AssetServiceGrpcTransport, grpc_helpers), - (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), - ], -) -@requires_api_core_lt_1_26_0 -def test_asset_service_transport_create_channel_user_scopes( - 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", - scopes=["1", "2"], - 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], @@ -1056,7 +998,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas "squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_channel_creds, quota_project_id=None, options=[ @@ -1160,7 +1102,7 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ "mtls.squid.clam.whelk:443", credentials=cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ @@ -1204,7 +1146,7 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): "mtls.squid.clam.whelk:443", credentials=mock_cred, credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, ssl_credentials=mock_ssl_cred, quota_project_id=None, options=[ From 0bdd24811fd1dc6ad15241da98921992e208a848 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Wed, 30 Jun 2021 00:38:33 +0000 Subject: [PATCH 3/3] fix: require google-api-core>=1.26.0 --- setup.py | 2 +- testing/constraints-3.6.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 533d03da..cda44c11 100644 --- a/setup.py +++ b/setup.py @@ -28,7 +28,7 @@ # 'Development Status :: 5 - Production/Stable' release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "google-api-core[grpc] >= 1.26.0, < 2.0.0dev", "grpc-google-iam-v1 >= 0.12.3, < 0.13dev", "google-cloud-access-context-manager >= 0.1.2, < 0.2.0dev", "google-cloud-org-policy>=0.1.2, <0.4.0", diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 1d8ebd1b..d2b9a053 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -5,7 +5,7 @@ # # e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", # Then this file should have foo==1.14.0 -google-api-core==1.22.2 +google-api-core==1.26.0 grpc-google-iam-v1==0.12.3 google-cloud-access-context-manager==0.1.2 google-cloud-org-policy==0.1.2